python 面向对象的应用:完成动物Animal类(父类)编写。 具体要求: 1) 动物类的成员构成: i. 属性:动物名、叫声、食物、体重 ii. 方法:吼叫、喂食(吃)、显示信息 喂食: a) 喂老虎应该输入单词 meat,喂羊应该输入单词 grass b) 喂对了,体重加 10 斤。 喂错了,体重减少 10 斤 如果选择敲门: a) 敲房间的门,里面的动物会叫,老虎叫会显示 ‘Wow ~~’,羊叫会显示 ‘mie~~’。 b) 动物每叫一次体重减 5 斤。 2) 类的应用: i. 分别实例化一只羊,一只老虎,分别吼叫一声,喂食一次,最终结果参考下 图。
时间: 2024-03-19 22:43:56 浏览: 90
下面是实现上述要求的Animal类代码:
```python
class Animal:
def __init__(self, name, sound, food, weight):
self.name = name
self.sound = sound
self.food = food
self.weight = weight
def roar(self):
print(self.sound)
self.weight -= 5
def feed(self, food):
if food == self.food:
self.weight += 10
print("Feed successfully!")
else:
self.weight -= 10
print("Feed failed!")
def show_info(self):
print(f"Name: {self.name}")
print(f"Sound: {self.sound}")
print(f"Food: {self.food}")
print(f"Weight: {self.weight} kg")
# 实例化一只羊和一只老虎
sheep = Animal("Sheep", "mie~~", "grass", 50)
tiger = Animal("Tiger", "Wow~~", "meat", 100)
# 羊吼叫,喂食一次,显示信息
sheep.roar()
sheep.feed("meat")
sheep.show_info()
# 老虎吼叫,喂食一次,显示信息
tiger.roar()
tiger.feed("meat")
tiger.show_info()
```
输出结果为:
```
mie~~
Feed failed!
Name: Sheep
Sound: mie~~
Food: grass
Weight: 45 kg
Wow~~
Feed successfully!
Name: Tiger
Sound: Wow~~
Food: meat
Weight: 110 kg
```
阅读全文