我是Stack的新手,我正在python中编写这个程序,它应该创建两个不同的游戏板对象:一个小对象和一个大对象。两个游戏板对象都是由列表组成的,因此我可以稍后通过索引访问板上的特定空间。较大的一块板没有任何明显的错误,但是当我创建小板对象并尝试通过索引访问它们的特定空间时,我得到错误'对象不支持索引。我真的很困惑,因为它与大板一起工作,我已经完成了关于这个错误的大量其他帖子,但他们似乎都发现对象中的错误不是真正的列表。但是我在构造函数中定义它应该是一个列表。我希望你们能帮忙!
以下是类的代码:
import copy
SMALL_BOARD = [ #one list for small board
None, None, None,
None, None, None,
None, None, None,
]
BIG_BOARD = [ #one big list for big board
None, None, None, None, None, None,
None, None, None, None, None, None,
None, None, None, None, None, None,
None, None, None, None, None, None,
None, None, None, None, None, None,
None, None, None, None, None, None,
]
class SMALLBoard():
def __init__(self, board=None):
if board is None:
board = copy.deepcopy(SMALL_BOARD)
self.sboard = board
class BIGBoard():
def __init__(self, bboard=None):
if bboard is None:
bboard = copy.deepcopy(BIG_BOARD)
self.bboard = bboard
def equal_small_boards(self, boardA, boardB, boardC, boardD):
tempboard=BIGBoard()
tempboard[0]= boardA[0]
tempboard[3]= boardB[0]
tempboard[18]= boardC[0]
tempboard[21]= boardD[0]
return tempboard
当我运行以下代码时,我得到错误:'在equal_small_boards中 tempboard [0] = boardA [0] TypeError:'SMALLBoard'对象不支持索引'
bboard = BIGBoard()
sboardA = SMALLBoard()
sboardB = SMALLBoard()
sboardC = SMALLBoard()
sboardD = SMALLBoard()
bboard=bboard.equal_small_boards(sboardA, sboardB, sboardC, sboardD)
提前感谢您的回答! :)
答案 0 :(得分:1)
问题出现在您的方法上:
def equal_small_boards(self, boardA, boardB, boardC, boardD):
tempboard=BIGBoard()
tempboard[0]= boardA[0]
tempboard[3]= boardB[0]
tempboard[18]= boardC[0]
tempboard[21]= boardD[0]
return tempboard
tempboard
是BIGBoard
,BIGBoard
不支持编制索引。您可能想要写入bboard
字段。所以:
def equal_small_boards(self, boardA, boardB, boardC, boardD):
tempboard = BIGBoard()
tempboard.bboard[0] = boardA[0]
tempboard.bboard[3] = boardB[0]
tempboard.bboard[18] = boardC[0]
tempboard.bboard[21] = boardD[0]
return tempboard
应该工作。