编写一个类Animal,描述动物的属性和行为,通过继承Animal类定义Bird类、Fish类,分别描述鸟类 和鱼类的属性和行为,具体要求如下:(1)Animal类定义属性name、color、foot Nurnber,描述动物的名称、颜色、脚的只数;定义成员方法showInfo0,用于输出动物的属性信息;定义成员方法move0,用于描述动物如何行走(输出“可以通过飞、跑、游等方式移动身体〞;(2)通过继承Animal定义Bird类,改写 父类的move方法(输出“通过飞来移动身体”),增加一个方法nest0用于描述在哪里筑巢;(3)通过继承 Animal定义Fis类,改写父类的move方法(输出"通过游来移动身体”,增加一个属性length,用于描述 鱼的身长,改写父类的shorolnfo0方法,除了输出 narme、color、foot Number属性,还要输出鱼的身长;(4)编写测试类,分别创建上述3个类的对象,并给对象的所有属性赋值,调用对象的所有方法。
时间: 2023-06-27 20:05:11 浏览: 275
java类的重用
下面是对应的代码实现:
```python
class Animal:
def __init__(self, name, color, foot_number):
self.name = name
self.color = color
self.foot_number = foot_number
def show_info(self):
print(f"Name: {self.name}\nColor: {self.color}\nFoot Number: {self.foot_number}")
def move(self):
print("Can move by flying, running, swimming, etc.")
class Bird(Animal):
def __init__(self, name, color, foot_number):
super().__init__(name, color, foot_number)
def move(self):
print("Can move by flying.")
def nest(self, place):
print(f"{self.name} builds nest on {place}")
class Fish(Animal):
def __init__(self, name, color, foot_number, length):
super().__init__(name, color, foot_number)
self.length = length
def show_info(self):
super().show_info()
print(f"Length: {self.length}")
def move(self):
print("Can move by swimming.")
# Testing
bird = Bird("Sparrow", "Brown", 2)
bird.show_info()
bird.move()
bird.nest("Tree")
fish = Fish("Salmon", "Pink", 0, 20)
fish.show_info()
fish.move()
animal = Animal("Tiger", "Orange", 4)
animal.show_info()
animal.move()
```
输出结果:
```
Name: Sparrow
Color: Brown
Foot Number: 2
Can move by flying.
Sparrow builds nest on Tree
Name: Salmon
Color: Pink
Foot Number: 0
Length: 20
Can move by swimming.
Name: Tiger
Color: Orange
Foot Number: 4
Can move by flying, running, swimming, etc.
```
阅读全文