# 创建Animal类作为基础类
class Animal:
def __init__(self, name):
self.name = name
def make_sound(self):
pass
# 创建Dog类作为Animal类的子类
class Dog(Animal):
def make_sound(self):
return "Woof!"
# 创建Cat类作为Animal类的子类
class Cat(Animal):
def make_sound(self):
return "Meow!"
# 使用多态展示不同子类的make_sound方法
def animal_sound(animal):
print(animal.make_sound())
# 创建Animal实例并调用make_sound方法
animal = Animal("Generic Animal")
print(animal.make_sound())
# 创建Dog实例并调用make_sound方法
dog = Dog("Buddy")
print(dog.make_sound())
# 创建Cat实例并调用make_sound方法
cat = Cat("Whiskers")
print(cat.make_sound())
# 使用多态展示不同子类的make_sound方法
animal_sound(dog)
animal_sound(cat)
输出:
None
Woof!
Meow!
Woof!
Meow!
如何创建‘Animal‘类作为基础类,以及‘Dog‘和‘Cat‘类作为子类,展示继承和多态的基本应用
最新推荐文章于 2023-12-13 11:17:58 发布