【发布时间】:2015-01-28 16:38:16
【问题描述】:
我在 Kubuntu 14.04 中使用 Python 2.7.6;尝试(为了我自己的启迪)使用为每个单元实例化的单个类来实现康威的生活,以完成“细胞自动机”工作。在此过程中,我将一个实例存储在列表列表的每个成员中。问题是,当我在迭代列表的索引时尝试调用实例方法时,出现错误:TypeError: 'int' object has no attribute '__getitem__'。这是我的代码:
# Conway's Life in Python -- initially with text graphics, 50x50, possibly
# with actual windowing system graphics in a later version. Use a class
# replicated in quantity (2500!) for each cell to vastly simplify computation;
# is below worth it or not? Would bring all four cores into computation.
# learn how to do threading to let the cells calculate in parallel, but pass
# signals to keep them in step.
class Cell(object):
def __init__(self, coords, size):
# coords is a tuple of x, y; size is the field height/width in cells
self.position = coords
self.is_live = False
pass
def count_neighbors(self):
x,y = self.position
self.neighbors = 0
for i in range (-1, 1):
for j in range (-1, 1):
# add size and modulo (size - 1) to create wrapped edges
if field[(x + i + self.xy) % (self.xy - 1)] [(y + j +
self.xy) % (self.xy - 1)]:
++self.neighbors
pass
def live_or_die (self):
if self.neighbors < 2 or self.neighbors > 3:
self.is_live = False
elif self.neighbors == 3:
self.is_live = True
else:
pass
# main program
extent = 4 #size of field
# create list of lists of Cell objects w/ coord tuples
# for i in range extent:
# for j in range extent:
# field[i[j]] = (i,j)
field = [[Cell((i, j), extent) for j in range(extent)] for i in range(extent)]
# insert population setting here
# insert population setting here
for i in range (extent):
for j in range (extent):
field[i[j]].count_neighbors()
for i in range (extent):
for j in range (extent):
field[i[j]].live_or_die()
最后两个for 循环将被包裹在while 中,以便在我弄清楚如何创建初始种群并以受控方式停止程序后继续运行。显然,一旦我调试了迭代,extent 将被设置得更高(在向Cell 中的方法添加变量之前,50x50 仅使用了大约 5.5 MiB RAM,所以我应该能够以单图形模式下的像素,如果这不会太慢的话——每秒几步对我来说已经足够快了)。
问题是,我没有看到单独调用存储在field 中的Cell 实例的方法。我认为这里的问题是我如何嵌套列表,但它们必须嵌套,不是吗? j 列表是 i 列表的成员。
完整的追溯:
Traceback (most recent call last):
File "PyLife.py", line 51, in <module>
field[i[j]].count_neighbors()
TypeError: 'int' object has no attribute '__getitem__'
【问题讨论】:
-
你能告诉我们完整的追溯吗?
-
添加了完整的回溯。我在粘贴代码时更改了
count_neighbors变量范围,现在我得到了一个不同的错误;我要把它改回以前的样子。 -
好的,我发现了问题(我认为):我在索引
field [i[j]]的地方,我应该将它作为field [i][j]进行——至少,这样做消除了错误消息和程序完成。现在来看看逻辑是否正常工作......
标签: python list class instance