羊老虎 面向对象 喂养
# 羊 老虎 import random # 动物 class Animal(): def __init__(self,animal,weight,call,food,room_num): self._animal = animal self._weight = weight self._call = call self._food = food self._room_num = room_num def eat(self,food): if food==self._food: self._weight += 10 else: self._weight -=10 print(f'{self._animal}吃了{food},当前体重{self._weight}') def call(self): self._weight -= 5 print(f'{self._animal}叫了{self._call},当前体重{self._weight}') def get_weight(self): print(f'{self._animal},当前体重{self._weight}') return self._weight # 老虎继承 动物 class Tiger(Animal): def __init__(self,room_num): super().__init__("tiger",200,"wow","meat",room_num) # 羊继承 动物 class Sheep(Animal): def __init__(self,room_num): super().__init__("sheep",100,"mie","grass",room_num) # 饲养员 class Keeper(): # 属性 def __init__(self): # 常量 self.dict_room={}#{房间号,动物类} # 方法 放入动物 def put_animal(self): for room_num in range(1,10): animal_type=random.choice([Tiger,Sheep])# 动物类有两种 老虎和羊 # 实例化一个动物 老虎或者羊类时,传入房间号参数 animal=animal_type(room_num)# animal=Sheep(0) # 放入字典 self.dict_room[room_num]=animal # 方法 喂养动物 def keep(self): for room_num,animal in self.dict_room.items(): animal.get_weight() animal.call() animal.eat(animal._food) animal.get_weight() # 实例化 k=Keeper() k.put_animal() k.keep()