如何在MCNode类中调用Board类属性?解决AttributeError异常
问题:MCNode类访问Board属性时触发AttributeError报错
报错信息:
AttributeError: 'MCNode' object has no attribute 'board'
尝试在MCNode类的方法中访问Board类的属性时出现上述错误,相关代码如下:
class StudentAI(): def __init__(self,col,row,p): self.col = col self.row = row self.p = p self.board = Board(col,row,p) self.board.initialize_game() self.color = '' self.opponent = {1:2, 2:1} self.color = 2 class MCNode(): parent = None boardstate = None gameboard = None col = 0 row = 0 p = 0 children = [] color = 2 # whitewon = 0 # blackwon = 0 wins = 0 game_color = 0 depth = 0 maxdepth = 15 visits = 0 c = math.sqrt(2) opponent = {1:2,2:1} def __init__(self, boardstate, gameboard, col, row, color, game_color, parent=None): if parent != None: self.parent = parent self.depth = parent.depth + 1 self.children = [] self.col = col self.row = row # boardstate will be static copy of board stored in every node self.boardstate = boardstate # gameboard will be the board which constantly changes self.gameboard = gameboard self.game_color = game_color self.color = color # self.whitewon = 0 # self.blackwon = 0 self.wins = 0 self.visits = 0 self.maxdepth = 15 self.opponent = {1:2,2:1}
在MCNode类的某个方法中执行以下代码时触发报错:
current_piece = self.board.board[c][r]
需求:在MCNode类的方法中访问Board类的属性,如何调整代码实现?
解决方案
核心原因
报错是因为MCNode实例未定义board属性,你混淆了属性名称——MCNode初始化时已经接收并存储了Board实例到self.gameboard中,而非self.board。
具体调整步骤
修改属性调用名称:
将方法中的self.board替换为self.gameboard,对应代码修改为:current_piece = self.gameboard.board[c][r]确保
gameboard参数正确传入:
创建MCNode实例时,需传入有效的Board实例。例如在StudentAI类中创建节点时,传递自身的self.board:# 示例:在StudentAI的方法中创建MCNode new_node = MCNode( boardstate=..., # 传入对应的boardstate参数 gameboard=self.board, # 传递StudentAI持有的Board实例 col=self.col, row=self.row, color=self.color, game_color=... # 传入对应的game_color参数 )清理冗余类属性(可选):
MCNode类顶部定义的gameboard = None是类属性,会被实例属性覆盖,可删除避免混淆,仅保留实例属性的赋值逻辑。
内容的提问来源于stack exchange,提问作者schnuggyy
相关产品推荐
相关产品推荐

