# 羊 老虎 饲养员 import random # 基类 class Animal(): # 属性 def __init__(self,animal,w,call,food,room_num): self._animal=animal self._w=w self._call=call self._food=food self._room_num=room_num # 动作 吃 def eat(self,food): print(f'{self._animal}吃了{food},当前的体重是{self._w}') # 动作 叫 def call(self): print(f'{self._animal}叫了{self._call},当前的体重是{self._w}') def get_w(self): print(f'在第{self._room_num}房间,{self._animal},当前的体重是{self._w}') return self._w # 继承基类 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._rooms={} def put_animal(self): # 10个房间10个动物 for room_num in range(1,11): # 动物有两种 随机放 animal=random.choice([Tiger,Sheep]) # 追加到字典 self._rooms[room_num] = animal(room_num) return self._rooms def keep(self): # 对10个动物喂养 for room_num,animal in self._rooms.items(): animal.get_w() animal.call() animal.eat(animal._food) k=Keeper() k.put_animal() k.keep()
标签:Sheep,__,room,self,random,num,animal,._ From: https://www.cnblogs.com/haha1988/p/17584562.html