你好,我在通过循环创建对象时无法使属性的值每次随机。我想要实现的目标是每次实例化一个对象时,每个对象的self.hunger和self.boredom都具有从0到20不同的值,但每次通过for循环打印critters字典时,它们的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.")
如果你希望整个程序能够理解我的问题,我会编辑我的问题。请帮助我。
=None
,并在构造函数中运行arg=def_value if arg is None else arg
。 - Serge Seredenko