1 回答
TA贡献1893条经验 获得超10个赞
这个:
class chessBoard:
BOARD = None
BOARD_WIDTH = 8
def __init__(self,W = 8):
self.BOARD = []
self.BOARD_WIDTH = W
aRow = ['.'] * self.BOARD_WIDTH # this is one list, it's a reference to data
for curRow in range(self.BOARD_WIDTH):
self.BOARD.append(aRow) # adds the same reference 8 times
您的列表包含 8 次相同的参考,如果您通过一个参考更改数据,则其他参考(至多相同)也会反映这一点。所有引用都指向相同的数据。
用
self.BOARD.append(['.'] * self.BOARD_WIDTH) # add "unique" lists instead
您可以检查id()的:
# your version ( self.BOARD.append(aRow) )
print(list(map(id,myChessBoard.BOARD)))
[140415825494600, 140415825494600, 140415825494600, 140415825494600,
140415825494600, 140415825494600, 140415825494600, 140415825494600]
# fixed version (self.BOARD.append(['.'] * self.BOARD_WIDTH))
[140560309994568, 140560309994440, 140560309994376, 140560309994312,
140560309994248, 140560309994184, 140560309994120, 140560309994696]
添加回答
举报