如何通过python中的for循环创建具有随机属性值的对象?
美好的一天,每次我通过for循环创建一个对象时,我无法使我的属性值随机.我在这段代码中的目标是,当我实例化一个对象时,每个对象的self.hunger和self.boredom都有不同的值,从0到20,但每次我通过for循环打印生物字典时,他们的self.hunger和self.boredom是一样的.我该如何随意制作?你能解释一下为什么我的代码不起作用吗?这是我的一些代码.任何答案都非常感谢.
class Critter(object):
"""A virtual pet"""
import random
def __init__(self, name, hunger = random.randrange(0, 21), boredom = random.randrange(0, 21)):
self.name = name
self.hunger = hunger
self.boredom = boredom
def __str__(self):
rep = "\nCritter object\n"
rep += "Name: " + str(self.name) + ", Hunger: " + str(self.hunger) + ", Boredom: " + str(self.boredom)
return rep
def main():
critters = {}
crit_name = input("What do you want to name to your critter?: ")
critters[1] = Critter(crit_name)
choice = None
while choice != "0":
print \
("""
Critter Caretaker
0 - Quit
1 - Listen to your critters
2 - Feed your critters
3 - Play with your critters
4 - Create another critter
""")
elif choice == "4":
crit_name = input("What do you want to name your critter?: ")
for i in range(len(critters) + 1, 11):
critters[i] = Critter(crit_name)
break
if i == 10:
print("\nMaximum critters reached. Cannot create another critter.")
如果你想让整个程序理解我的问题,我会编辑我的问题.请帮我.