类多态(Class Polymorphism)是面向对象编程中的一个重要概念,它允许我们使用父类的引用变量来引用子类的对象,从而实现不同子类对象的统一处理。
在Python中,类多态可以通过以下方式实现:
1. 继承:子类可以继承父类的方法和属性,并且可以重写父类的方法,即子类可以拥有自己的实现逻辑。这样,当使用父类的引用变量引用子类的对象时,调用相同的方法名时,会根据具体的对象类型调用对应的方法。
2. 方法重写:子类可以重写(override)父类的方法,即在子类中重新实现父类的方法,并且使用相同的方法名。这样,当使用父类的引用变量引用子类的对象时,调用该方法时会调用子类中的实现。
下面是一个简单的示例代码:
```python
class Animal:
def sound(self):
print("Animal sound")
class Dog(Animal):
def sound(self):
print("Woof!")
class Cat(Animal):
def sound(self):
print("Meow!")
animal = Animal()
dog = Dog()
cat = Cat()
animal.sound() # 输出: "Animal sound"
dog.sound() # 输出: "Woof!"
cat.sound()