5.设计一个Animal(动物)类,包括颜色属性和叫方法。再设计一个Fish(鱼)类,包括尾巴和颜色两个属性,以及叫方法。要求:Fish类继承Animal类,重写构造方法和叫方法。
时间: 2024-02-25 10:57:02 浏览: 25
好的,以下是Animal类和Fish类的代码实现:
```python
class Animal:
def __init__(self, color):
self.color = color
def make_sound(self):
print("Animal makes sound.")
class Fish(Animal):
def __init__(self, color, tail):
super().__init__(color)
self.tail = tail
def make_sound(self):
print("Fish makes sound.")
```
在上面的代码中,Animal类有一个属性color和一个方法make_sound。Fish类继承Animal类,它有两个额外的属性tail和color,并重写了make_sound方法。重写的make_sound方法会输出“Fish makes sound.”。
这样,我们就可以创建一个Fish对象,并调用它的属性和方法:
```python
fish = Fish("red", "long")
print(fish.color) # Output: red
print(fish.tail) # Output: long
fish.make_sound() # Output: Fish makes sound.
```
注意,Fish类的构造方法重写了Animal类的构造方法,因此我们需要使用super()方法来调用Animal类的构造方法,以便初始化继承的属性。