我已經實際完成了這個練習(差不多),但是我只是在__str__
這個對象內停留在一個小問題上。如果我這樣做從對象中打印Python __str__
elif choice == "9":
try:
for i in sworm:
print(i)
except TypeError:
None`
然後將只打印出的第一個對象的細節在我的名單(只在有2個對象),例如 - sworm = [crit,crit1]
當我嘗試這樣做
elif choice == "9":
try:
print(sworm)
except TypeError:
None
然後我得到: -
[<__main__.Critter object at 0x02B54AD0>, <__main__.Critter object at 0x02B5B190>]
這裏是我的對象上半年
class Critter(object):
"""A virtual pet"""
def __init__(self, name, hunger = random.randint(1,50), boredom = random.randint(1,50)):
self.name = name
self.hunger = hunger
self.boredom = boredom
def __pass_time(self):
self.hunger += 1
self.boredom += 1
def __str__(self):
print ("Critter object\n")
print (self.name)
print (self.hunger)
print (self.boredom)
在此先感謝。
這是無關緊要的,但請注意,您的構造函數參數將僅被評估一次,而不是每個實例的創建(請參閱http://docs.python-guide.org/en/latest/writing/gotchas。html#mutable-default-arguments) – justinas