0
我已經在我的項目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行(print(ant_farm[0][0])
)
AttributeError: Ant_farm instance has no attribute '__getitem__'
。這是爲什麼?
你試圖讓''Ant_farm'的self.matrix'內容?如果是這樣,你需要在'Ant_farm'類中定義方法'__getitem__',或者返回'self.matrix [x] [y]'' – dragon2fly
''print'(ant_farm.matrix [0] [0])' ? –