polymorphism python coding sample for beginner, save in files,
Here's an example of polymorphism in Python, where we have a base class Animal with two derived classes Dog and Cat. Each of these classes implements their own speak() method, which is an example of polymorphism.
# Define the Animal base class
class Animal:
def speak(self):
pass
# Define the Dog class, which overrides the speak() method
class Dog(Animal):
def speak(self):
return "Woof!"
# Define the Cat class, which overrides the speak() method
class Cat(Animal):
def speak(self):
return "Meow!"
# Create instances of the Dog and Cat classes
my_dog = Dog()
my_cat = Cat()
# Call the speak() method on both instances, which will return different results
print(my_dog.speak()) # Outputs "Woof!"
print(my_cat.speak()) # Outputs "Meow!"
# Save the output to a file
with open('output.txt', 'w') as f:
f.write(my_dog.speak() + '\n')
f.write(my_cat.speak() + '\n')
In this example, we define the Animal base class with a speak() method that doesn't do anything, because we want to leave it up to the derived classes to override this method with their own implementation.
We then define the Dog and Cat classes, which both inherit from Animal and override the speak() method to return different results. We create instances of these classes and call the speak() method on each one, which demonstrates polymorphism in action.
Finally, we save the output to a file using Python's built-in open() function and a with block, which automatically handles closing the file when we're done writing to it. We write each animal's speak() output to a separate line in the file using the newline character \n.
原文地址: https://www.cveoy.top/t/topic/si6 著作权归作者所有。请勿转载和采集!