类的继承!

定义了一个Animal类和它的三个子类:Lion、Tiger和Elephant。Animal类有三个方法:eat()、sleep()和speak(),而每个子类都继承了这些方法并且有自己的属性和方法。

  • Lion类有一个额外的属性 mane_color(鬃毛颜色),并且重写了speak()方法来输出"Lion is Roaring"。
  • Tiger类有一个额外的属性 stripe_pattern(条纹图案),并且重写了speak()方法来输出"Tiger is Growling"。
  • Elephant类有一个额外的属性 trunk_length(象鼻长度),并且重写了speak()方法来输出"Elephant is Trumpeting"。

下面是运行的详细代码

class Animal:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def eat(self):
        print(f"{self.name} is eating.")
    def sleep(self):
        print(f"{self.name} is sleeping.")
    def speak(self):
        print(f"{self.name} is speaking.")

class Lion(Animal):
    def __init__(self, name, age, mane_color):
        super().__init__(name, age)
        self.mane_color = mane_color
    def speak(self):
        print(f"{self.name} is Roaring.")

class Tiger(Animal):
    def __init__(self, name, age, stripe_pattern):
        super().__init__(name, age)
        self.stripe_pattern = stripe_pattern
    def speak(self):
        print(f"{self.name} is Growling")

class Elephant(Animal):
    def __init__(self, name, age, trunk_length):
        super().__init__(name, age)
        self.trunk_length = trunk_length
    def speak(self):
        print(f"{self.name} is Trumpeting")

lion = Lion("The Lion", 5, "brown")
tiger = Tiger("The Tiger", 3, "orange and black")
elephant = Elephant("The Elephant", 8, "2 meters")

print(f"\nLion details: Name is {lion.name}, Age is {lion.age}, Mane Color is {lion.mane_color}")
lion.eat()
lion.speak()
lion.sleep()

print(f"\nTiger details: Name is {tiger.name}, Age is {tiger.age}, Stripe Pattern is {tiger.stripe_pattern}")
tiger.eat()
tiger.speak()
tiger.sleep()

print(f"\nElephant details: Name is {elephant.name}, Age is {elephant.age}, Trunk Length is {elephant.trunk_length}")
elephant.eat()
elephant.speak()
elephant.sleep()

在主程序中,创建了一个Lion对象、一个Tiger对象和一个Elephant对象,并分别打印它们的详细信息(名称、年龄和特有属性)。然后调用它们的eat()、speak()和sleep()方法,分别输出它们正在吃东西、发出声音和睡觉。

运行结果:

  • 16
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值