如何创建‘Animal‘类作为基础类,以及‘Dog‘和‘Cat‘类作为子类,展示继承和多态的基本应用

# 创建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!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值