python“;“对象不可调用”;尽管在其他地方使用相同的代码
我有一个叫做python“;“对象不可调用”;尽管在其他地方使用相同的代码,python,Python,我有一个叫做cell的类: class cell: def __init__(self, row, column, state): self.x = column * 20 self.y = row * 20 self.state = state 我有一个使用嵌套for循环创建的单元格列表: grid = [] for x in range(20): for y in range(20): grid.append(cell(x, y, bool(
cell
的类:
class cell:
def __init__(self, row, column, state):
self.x = column * 20
self.y = row * 20
self.state = state
我有一个使用嵌套for循环创建的单元格列表
:
grid = []
for x in range(20):
for y in range(20):
grid.append(cell(x, y, bool(random.getrandbits(1))))
我可以使用cell()
将单元格附加到此网格,而不会出现任何问题
稍后,我有一个名为CalculateNextGrid()
的子例程,它创建单元格列表并将其作为输出返回
def CalculateNextGrid(grid):
output = []
index = 0
row = 0
column = 0
for cell in grid:
print(grid)
neighbors = CountCells(index, grid, 20)
if cell.state == True:
if neighbors < 2 or neighbors > 3:
output.append(cell(row, column, False))
grid.append(cell(x, y, bool(random.getrandbits(1))))
else:
output.append(cell(row, column, True))
else:
if neighbors == 3:
output.append(cell(row, column, True))
else:
output.append(cell(row, column, False))
row += 1
if row == 20:
row = 0
column += 1
return output
def CalculateNextGrid(网格):
输出=[]
索引=0
行=0
列=0
对于网格中的单元格:
打印(网格)
邻居=计数单元(索引,网格,20)
如果cell.state==True:
如果邻居<2或邻居>3:
append(单元格(行、列、假))
追加(单元格(x,y,bool(random.getrandbits(1)))
其他:
append(单元格(行、列、真))
其他:
如果邻居==3:
append(单元格(行、列、真))
其他:
append(单元格(行、列、假))
行+=1
如果行==20:
行=0
列+=1
返回输出
当我使用output.append()将单元格添加到列表中时,python抛出一个“cell object not callable”错误,尽管它在前面的代码中工作。为什么会这样
这里
for cell in grid
您正在将名称单元格
用于其他内容。在该点之后,它不再适用于单元格
类
你应该大写你的类名,
Cell
,这样它就不会与一个单独的Cell
变量冲突。对于网格中的Cell
——你正在使用名称Cell
来做其他事情。(这也是您应该将类名大写的部分原因,例如,单元格
)或将网格重命名为单元格<代码>用于单元格中的c