class Room:
def init(self, no, dongwu):
self.no = no
self.dongwu = dongwu # 动物类对象
if name == 'main':
# 生成是个房间,将动物和房间绑定
rooms = [] # 保持十个房间
for i in range(1, 11):
if random.randint(0,1) == 1:
animal = Tiger(f'胖虎{i}')
else:
animal = Sheep(f'喜洋洋{i}')
r = Room(i, animal)
rooms.append(r)
for i in rooms:
print(i.no,i.dongwu.name)
** print(i.no,i.dongwu.name) 会输出 i **
因为在dongwu.name 里面把i也加进去了 animal = Tiger(f'胖虎{i}') ,就是这个{i}
i.dongwu.name
i是Room里一个一个循环取出的元素,dongwu.nama是类的属性,也就是动物名字,定义在Sheep(f'喜洋洋{i}')这里
望采纳!谢谢