Python Polymorphism: Beginner's Guide with Code Example
Here's a simple example of polymorphism in Python:
class Animal:
def __init__(self, name):
self.name = name
def make_sound(self):
pass
class Dog(Animal):
def make_sound(self):
print(self.name + ' barks')
class Cat(Animal):
def make_sound(self):
print(self.name + ' meows')
class Bird(Animal):
def make_sound(self):
print(self.name + ' chirps')
# create some animals
dog1 = Dog('Fido')
cat1 = Cat('Whiskers')
bird1 = Bird('Tweety')
# make them all make a sound
for animal in [dog1, cat1, bird1]:
animal.make_sound()
In this example, we have a base class 'Animal' with a 'make_sound' method that doesn't do anything (it's just a placeholder). We then have three subclasses of 'Animal', 'Dog', 'Cat', and 'Bird', each of which overrides the 'make_sound' method to make the appropriate sound for that type of animal.
We then create some instances of each of these classes, and use a 'for' loop to call the 'make_sound' method on each of them. Because each instance is of a different class, the 'make_sound' method gets called in a different way for each one, demonstrating polymorphism.
原文地址: https://www.cveoy.top/t/topic/lEeC 著作权归作者所有。请勿转载和采集!