任务二:实现多态(继承) 1. 设计一个动物类Animal,定义其属性name及weight,再定义一个带有名称及重量两个参数的构造方法,成员方法eat()、sleep()、breathe()、info()。 2. 设计动物类的子类Sheep以及Wolf,再分
时间: 2023-06-23 19:08:39 浏览: 139
别实现它们的特有属性和方法。
1. Animal类的实现
```python
class Animal:
def __init__(self, name, weight):
self.name = name
self.weight = weight
def eat(self):
print(f"{self.name} is eating.")
def sleep(self):
print(f"{self.name} is sleeping.")
def breathe(self):
print(f"{self.name} is breathing.")
def info(self):
print(f"Name: {self.name}, Weight: {self.weight}")
```
2. Sheep和Wolf类的实现
```python
class Sheep(Animal):
def __init__(self, name, weight, wool_color):
super().__init__(name, weight)
self.wool_color = wool_color
def produce_wool(self):
print(f"{self.name} produces {self.wool_color} wool.")
class Wolf(Animal):
def __init__(self, name, weight, pack_size):
super().__init__(name, weight)
self.pack_size = pack_size
def hunt(self):
print(f"{self.name} hunts with pack size of {self.pack_size}.")
```
在Sheep和Wolf类中,我们使用了继承来继承了Animal类的属性和方法,并且添加了各自特有的属性和方法。
现在我们可以创建Sheep和Wolf的实例,并调用它们的方法了:
```python
sheep = Sheep("Dolly", 50, "white")
wolf = Wolf("Luna", 70, 5)
sheep.info()
sheep.eat()
sheep.produce_wool()
wolf.info()
wolf.breathe()
wolf.hunt()
```
输出:
```
Name: Dolly, Weight: 50
Dolly is eating.
Dolly produces white wool.
Name: Luna, Weight: 70
Luna is breathing.
Luna hunts with pack size of 5.
```
阅读全文