# 定义一个父类
class Animal:
def __init__(self, name):
self.name = name
def eat(self):
print(f"{self.name} is eating.")
def sleep(self):
print(f"{self.name} is sleeping.")
# 定义一个子类,继承自Animal类
class Dog(Animal):
def __init__(self, name, breed):
# 调用父类的构造函数
super().__init__(name)
self.breed = breed
def bark(self):
print(f"{self.name} is barking!")
# 重写父类的方法
def eat(self):
print(f"{self.name} is eating dog food.")
多态是指不同的子类对象调用相同的父类方法,产生不同的执行结果,增加了代码的灵活性和可读性。多态以继承和重写父类方法为前提,也可以通过鸭子类型来实现。鸭子类型是指不关注对象的类型,而只关注对象的行为,如果一个对象具有某种行为,就可以当作某种类型来使用。例如:
# 定义一个函数,接受一个Animal类型的参数
def animal_action(animal):
animal.eat()
animal.sleep()
# 创建一个Dog对象和一个cat对象
dog = Dog("Buddy", "Golden Retriever")
cat = Cat("Kitty", "Persian")
# 调用函数,传入不同的对象
animal_action(dog)
animal_action(cat)
# 输出结果:
Buddy is eating dog food.
Buddy is sleeping.
Kitty is eating cat food.
Kitty is sleeping.