Python Polymorphism: Code Example & Explanation
Polymorphism in Python is the ability of an object to take on many forms. It's a concept that allows us to use a single interface to represent different types of objects. Here's a code sample demonstrating polymorphism in Python:
# Parent class
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
raise NotImplementedError('Subclass must implement abstract method')
# Child classes
class Dog(Animal):
def speak(self):
return self.name + ' barks'
class Cat(Animal):
def speak(self):
return self.name + ' meows'
class Cow(Animal):
def speak(self):
return self.name + ' moos'
# Instantiate objects
dog = Dog('Buddy')
cat = Cat('Whiskers')
cow = Cow('Bessie')
# Call speak method on each object
print(dog.speak())
print(cat.speak())
print(cow.speak())
In this code, we have a parent class called 'Animal' and three child classes: 'Dog', 'Cat', and 'Cow'. Each child class has its own implementation of the 'speak' method, which returns a string representing the animal's sound.
We then create objects from each child class and call the 'speak' method on them. Since each object is from a different class, calling 'speak' results in different output strings. This showcases polymorphism, where a single interface (the 'speak' method) can be used to represent various object types ('Dog', 'Cat', and 'Cow').
原文地址: https://www.cveoy.top/t/topic/lEex 著作权归作者所有。请勿转载和采集!