1

I am trying to create a class Tile and use it in another method. However, when I run the code (below), the error is raised: AttributeError: type object 'Tile' has no attribute 'row'.

As I pop the class from the queue (Python list) and try to print it, it prints the value of the row (which is 0) but then gives the AttributeError.

Why is it saying that the attribute row does not exist?

""" Shortest distance between two cells in a matrix or grid """ class Tile: def __init__(self, row, col, dist): self.row = row self.col = col self.dist = dist def min_path(rows, cols, lot): start_node = Tile(0, 0, 0) q = [] q.append(start_node) visited = [[False]*cols for i in range(rows)] for i in range(rows): for j in range(cols): if lot[i][j] == 0: visited[i][j] = True while q: new_tile = q.pop(0) print(new_tile.row) if lot[new_tile.row][new_tile.col] == 9: return new_tile.dist if new_tile.row - 1 >= 0 and visited[new_tile.row - 1][new_tile.col] == False: Tile(new_tile.row - 1, new_tile.col, new_tile.dist + 1) q.append(Tile) visited[new_tile.row - 1][new_tile.col] = True if new_tile.row + 1 < rows and visited[new_tile.row + 1][new_tile.col] == False: Tile(new_tile.row + 1, new_tile.col, new_tile.dist + 1) q.append(Tile) visited[new_tile.row + 1][new_tile.col] = True if new_tile.col - 1 >= 0 and visited[new_tile.row][new_tile.col - 1] == False: Tile(new_tile.row, new_tile.col - 1, new_tile.dist + 1) q.append(Tile) visited[new_tile.row][new_tile.col - 1] = True if new_tile.col + 1 < cols and visited[new_tile.row][new_tile.col + 1] == False: Tile(new_tile.row, new_tile.col + 1, new_tile.dist + 1) q.append(Tile) visited[new_tile.row][new_tile.col + 1] = True return -1 if __name__ == "__main__": lot = [ [1, 0, 0, 0], [1, 0, 1, 0], [1, 1, 0, 0], [0, 1, 9, 0], ] result = min_path(4, 4, lot) print(result) 

When I run this file, this is the output:

0 Traceback (most recent call last): File "code.py", line 568, in <module> result = min_path(4, 4, lot) File "code.py", line 533, in min_path print(new_tile.row) AttributeError: type object 'Tile' has no attribute 'row' 

1 Answer 1

2

Seems to be because of these lines: q.append(Tile). You are appending a reference to the class itself instead of an instance of it. Instead try something like

tile = Tile(new_tile.row - 1, new_tile.col, new_tile.dist + 1) q.append(tile) 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.