我正在尝试创建一个Tile类,并在另一种方法中使用它。但是,当我运行下面的代码时,会引发错误:AttributeError: type object 'Tile' has no attribute 'row'
。
当我从队列(Python列表)中弹出类并尝试打印时,它会打印该行的值(为0),但会给出AttributeError。
为什么说属性行不存在?
"""
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)
当我运行此文件时,这是输出:
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'
答案 0 :(得分:2)
似乎是由于以下几行:q.append(Tile)
。您将对类本身的引用而不是其实例附加。而是尝试类似
tile = Tile(new_tile.row - 1, new_tile.col, new_tile.dist + 1)
q.append(tile)