我有以下井字游戏代码:
class TicTacToeBoard:
board = [[0,0,0], [0,0,0], [0,0,0]]
def printBoard(self):
print(self.board)
def putPiece(self, position1, position2):
self.board[position1][position2] = 1
我正在对代码进行单元测试,如下所示:
def testestablishTicTacToeBoard(self):
test = TicTacToeBoard()
self.assertEqual(test.board, [[0,0,0],[0,0,0],[0,0,0]])
def testPutPiece(self):
test = TicTacToeBoard()
self.assertEqual(test.board, [[0,0,0],[0,0,0],[0,0,0]])
test.putPiece(1,1)
self.assertEqual(test.board, [[0,0,0],[0,1,0],[0,0,0]])
在进行第二个单元测试之前,第一个单元测试顺利通过。一旦进行了第二个单元测试,第一个单元测试就不再通过:
self.assertEqual(test.board, [[0,0,0],[0,0,0],[0,0,0]])
AssertionError: Lists differ: [[0, 0, 0], [0, 1, 0], [0, 0, 0]] != [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
第二个单元测试中发生什么导致第一个不再通过?
答案 0 :(得分:2)
它看起来像是因为该板在所有实例之间共享(这是一个类属性,而不是实例属性)。
您可以使用它更改您的班级代码,它应该可以工作:
class TicTacToeBoard:
def __init__(self):
# Now each instance (self) has its own board:
self.board = [[0,0,0], [0,0,0], [0,0,0]]
def printBoard(self):
print(self.board)
def putPiece(self, position1, position2):
self.board[position1][position2] = 1
如果您想让自己相信发生了什么,可以比较两个版本(instance / class属性):
class TicTacToeBoard:
shared_board = [[0,0,0], [0,0,0], [0,0,0]]
def __init__(self):
self.board = [[0,0,0], [0,0,0], [0,0,0]]
def __str__(self):
return (
f"Instance board: {self.board}\n"
f"Class board (shared): {self.shared_board}"
)
def putPiece(self, position1, position2):
self.board[position1][position2] = 1
self.shared_board[position1][position2] = 2
>>> b1 = TicTacToeBoard()
>>> b2 = TicTacToeBoard()
>>> b1.putPiece(1, 2)
>>> print(b1)
Instance board: [[0, 0, 0], [0, 0, 1], [0, 0, 0]]
Class board (shared): [[0, 0, 0], [0, 0, 2], [0, 0, 0]]
>>> print(b2)
Instance board: [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
Class board (shared): [[0, 0, 0], [0, 0, 2], [0, 0, 0]]
请注意第二个脚板板b2
上没有一个,而(1, 2)
上有两个。