定义了一个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()方法,分别输出它们正在吃东西、发出声音和睡觉。