我的项目中有2个模块:
1- Ant.py
from threading import Thread
from Ant_farm import Ant_farm
ant_farm = Ant_farm(20, 20)
class Ant(Thread):
def __init__(self, x, y):
global ant_farm
Thread.__init__(self)
self.x = x
self.y = y
ant_farm.matrix[self.x][self.y] = True # At this point the arguments has initialized?
def move(self, x, y):
ant_farm.matrix[self.x][self.y] = False
self.x = x
self.y = y
ant_farm.matrix[self.x][self.y] = True # At this point the value has changed?
def run(self):
while True:
ant_farm.move_ant(self)
t = Ant(0, 0)
print(ant_farm[0][0])
t.move(1, 0)
2- Ant_farm.py
from threading import Condition
def matrix(x, y):
return [[False for j in range(y)] for i in range(x)]
class Ant_farm():
def __init__(self, x, y):
self.c = Condition() # I don't know if I have to put "self" before
self.matrix = matrix(x, y)
def move_ant(self, ant):
new_pos = {0: tuple(x0, y0 - 1),
1: tuple(x0 + 1, y0),
2: tuple(x0, y0 + 1),
3: tuple(x0 - 1, y0)}
x0, y0 = ant.x, ant.y
x1, y1 = new_pos[random.randrange(0, 4)]
with self.c:
try:
while self.matrix[x1][y1]:
self.c.wait()
self.matrix[x0][y0] = False
ant.move(x1, y1)
# It's not end and I have to review
except Exception: # Wich exceptions can appear?
pass
def __str__(self):
pass
两者都省略了评论。
当我执行Ant
模块时,引发此错误:
第27行(AttributeError:Ant_farm实例没有属性'__getitem __'
print(ant_farm[0][0])
)中的。为什么会这样?
答案 0 :(得分:0)
正如错误消息所示,您没有定义ant_farm[i]
是什么(函数__getitem__
)。
你可能想在Ant_farm
类中找到类似的东西:
def __getitem__(i):
return self.matrix[i]