【发布时间】:2016-11-21 05:32:49
【问题描述】:
我有一个小程序,它应该是细胞从出生到减数分裂到死亡的生命周期的基本模型。尽管我已经弄清楚了其中的大部分,但我仍然坚持以下几点:
class cell:
def __init__(self):
self.name = random.randint(1,1000)
self.type = [random.choice(b)]
self.age = 0
self.evos = random.randint(1,5) #<-- need to access this attr
def displayEvolutions(pop): # one of many methods, this one is a problem
p = []
for i in pop:
p.append(i.evos)
return p
community = [#a bunch of class instances]
cells_that_evolved = displayEvolutions(community)
它应该遍历类实例列表community,访问它们的evo 属性,用该数据填充cells_that_evolved,然后将该列表显示给用户。
应该是这样的:
cells_that_evolved = displayEvolutions(community)
print(cells_that_evolved)
[3, 4, 5, 6, 7, 8, 3, 1, 5] #<--- 9 instances, 9 values = instance.evos
但是,无论我尝试什么,它只会将第一个值附加到列表中,因此列表看起来像这样:
[3]
为什么?
【问题讨论】:
标签: python list class python-3.x for-loop