使用Python语言,设计一个鱼类,该类中有tail属性和color属性,以及一个call方法。让鱼类继承动物类,重写init和call方法
时间: 2024-03-10 12:49:02 浏览: 20
好的,以下是实现鱼类的Python代码:
```python
class Animal:
def __init__(self, color):
self.color = color
def call(self):
raise NotImplementedError("Subclass must implement abstract method")
class Fish(Animal):
def __init__(self, color, tail):
super().__init__(color)
self.tail = tail
def call(self):
return "I'm a fish!"
def swim(self):
return "I'm swimming!"
```
在这个例子中,我们定义了一个新的类 `Fish`,它继承自 `Animal` 类。我们重写了 `__init__` 方法,以添加一个新的属性 `tail`,并调用了父类的构造函数以初始化颜色属性。我们还重写了 `call` 方法,以返回一条鱼的描述。最后,我们添加了一个新的方法 `swim`,用于描述鱼游泳的行为。
你可以使用以下方式来创建一个 `Fish` 对象,并调用其方法:
```python
my_fish = Fish("blue", "long")
print(my_fish.color) # 输出 "blue"
print(my_fish.tail) # 输出 "long"
print(my_fish.call()) # 输出 "I'm a fish!"
print(my_fish.swim()) # 输出 "I'm swimming!"
```
这样,我们就成功地创建了一个鱼类,并使其继承自动物类。我们还重写了其构造函数和 `call` 方法,以添加新的属性和行为。