[Python] Can't print a self-made matrix outside of its module

Discussão em 'Python' iniciado por Stack, Fevereiro 24, 2025.

  1. Stack

    Stack Membro Participativo

    I have 2 modules in my project:

    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: # Which exceptions can appear?
    pass

    def __str__(self):
    pass


    In both omit the comments.

    When I execute the Ant module, raises this error:


    AttributeError: Ant_farm instance has no attribute '_getitem_'
    ​

    in the line 27 (print(ant_farm[0][0])). Why does this?

    Continue reading...

Compartilhe esta Página