【发布时间】:2020-07-11 22:49:17
【问题描述】:
所以,我目前正在编写一个随机生成网格迷宫的程序。以下代码段是网格的单个“单元”的类定义。我定义了2个getter方法get_row和get_col,它们可以检索单元格的坐标。我相信这就是问题所在。
class cell: #Node storing each cell of grid
def __init__(self, rowNum=None, colNum=None):
self.rowNum = rowNum
self.colNum = colNum
self.blocked = 0 # 0 denotes False, all cells are initially unblocked
self.f = 0 # Distance from start node
self.g = 0 # Distance from goal node
self.h = 0 # Total cost ( h = f + g )
self.parent = None
def get_row(self):
return self.rowNum
def get_col(self):
return self.colNum
def isBlocked(self):
if self.blocked == 0:
return 0
if self.blocked != 0:
return 1
然后,我使用下面的线段遍历网格,随机确定某些正方形作为起点和终点。我将这些坐标保存为start_row、start_col、end_row 和end_col。
# List containing all the unblocked cells
unblockedCells = [cell() for i in range(numUnblocked)]
start_row = -1
start_col = -1
end_row = -1
end_col = -1
# Randomly picks 2 unblocked cells to be the starting and ending point
def set_start_and_end():
global start_row
global start_col
global end_row
global end_col
ctr1 = 0
for i in range(totalRows):
for j in range(totalCols):
if cellsArray[i][j].blocked == 0:
unblockedCells[ctr1] = cellsArray[i][j]
ctr1 = ctr1+1
#Initialize start position
startIndex = random.randint(0,len(unblockedCells)-1)
start_row = unblockedCells[startIndex].get_row
start_col = unblockedCells[startIndex].get_col
#Initialize target position
endIndex = random.randint(0, len(unblockedCells)-1)
end_row = unblockedCells[endIndex].get_row
end_col = unblockedCells[endIndex].get_col
print("Start: (",start_row,", ",start_col,") End: (",end_row,", ",end_col,")")
set_start_and_end()
但是,当我稍后在程序中尝试访问 start_row 和 start_col 的值时,我收到错误 list indices must be integers, not instancemethod
我的问题是,为什么 start_row 和 start_col 被存储为 instancemethod 而不是整数?
【问题讨论】:
-
unblockedCells[startIndex].get_row是一个实例方法。您需要使用()准确调用方法,即unblockedCells[startIndex].get_row()是实例方法的返回值(即 int)。或者,您可以使用@property装饰您的吸气剂,然后您就不需要()。尽管您的 getter 方法毫无意义,因为self.rowNum等是公共成员。也不要使用global。此外,您的代码 sn-p 有大量变量似乎没有分配给任何地方? -
谢谢,那我应该改用 unblockedCells[startIndex].rowNum 吗?你能否解释一下如何使用@property
-
看我的回答。但是,是的,您应该只使用
unblockedCells[startIndex].rowNum,因为这些功能毫无意义。
标签: python python-2.7 oop a-star grid-search