利用继承类设计四个类:Animal类,Dog类,Cat类和Bird类 Animal具有名称、体重、身高等数据成员,吃、说话等方法成员 Dog继承Animal类,对吃、说话方法进行重写(按照狗的特点) Cat继承Animal类,对吃、说话方法进行重写(按照猫的特点) Bird继承Animal类,对吃、说话方法进行重写(按照鸟的特点) 动物园新进一批动物(5只),可以用空列表表达,列表中的每一个元素为一只动物,不同动物元素在生成对象的时候用各自的构造函数构造。 第一只狗 第二只猫 第三只狗 第四只鸟 第五只狗 用循环依次调用列表中每个元素的吃、说话方法,并输出
时间: 2024-02-25 11:59:09 浏览: 143
animal 类的继承
好的,这是一个利用继承类设计的小项目,我会根据你的问题来回答。
首先,我们先定义一个Animal类,它包含名称、体重、身高等数据成员,以及吃、说话等方法成员:
```python
class Animal:
def __init__(self, name, weight, height):
self.name = name
self.weight = weight
self.height = height
def eat(self):
print(f"{self.name} is eating.")
def speak(self):
print(f"{self.name} is speaking.")
```
然后,我们定义一个Dog类,继承自Animal类,并对吃、说话方法进行重写:
```python
class Dog(Animal):
def __init__(self, name, weight, height):
super().__init__(name, weight, height)
def eat(self):
print(f"{self.name} is eating bones.")
def speak(self):
print(f"{self.name} is barking.")
```
接下来,我们定义一个Cat类,继承自Animal类,并对吃、说话方法进行重写:
```python
class Cat(Animal):
def __init__(self, name, weight, height):
super().__init__(name, weight, height)
def eat(self):
print(f"{self.name} is eating fish.")
def speak(self):
print(f"{self.name} is meowing.")
```
最后,我们定义一个Bird类,继承自Animal类,并对吃、说话方法进行重写:
```python
class Bird(Animal):
def __init__(self, name, weight, height):
super().__init__(name, weight, height)
def eat(self):
print(f"{self.name} is eating seeds.")
def speak(self):
print(f"{self.name} is chirping.")
```
现在我们已经定义好了Animal类以及它的三个子类Dog、Cat和Bird,接下来我们可以创建动物园中的动物对象,并将它们放入一个列表中:
```python
animals = [Dog("First Dog", 20, 30),
Cat("Second Cat", 10, 20),
Dog("Third Dog", 25, 35),
Bird("Fourth Bird", 5, 10),
Dog("Fifth Dog", 15, 25)]
```
最后,我们可以用循环依次调用列表中每个元素的吃、说话方法,并输出:
```python
for animal in animals:
animal.eat()
animal.speak()
print()
```
这样就完成了这个小项目,输出如下:
```
First Dog is eating bones.
First Dog is barking.
Second Cat is eating fish.
Second Cat is meowing.
Third Dog is eating bones.
Third Dog is barking.
Fourth Bird is eating seeds.
Fourth Bird is chirping.
Fifth Dog is eating bones.
Fifth Dog is barking.
```
阅读全文