2024-06-11 19:03:00 发布
网友
我正在为我的学校项目做一个游戏。我正在使用pycharm,不知何故在print\u board函数中,我在board[0]下面得到了红线。它似乎无法在函数中获取板元素。如何打印print\u board函数中的board元素
class tictactoe: board = [0, 1, 2, 3, 4, 5, 6, 7, 8] def print_board(self): print(board[0])
board是一个类变量。将类名(我所做的)或self放在它前面以引用它。请参阅this以了解差异
board
self
class tictactoe: # this variable is shared between all instances # of tictactoe board = [0, 1, 2, 3, 4, 5, 6, 7, 8] def print_board(self): print(tictactoe.board[0]) t = tictactoe() t.print_board()
您应该在类函数中使用self.board:
self.board
class tictactoe: board = [0, 1, 2, 3, 4, 5, 6, 7, 8] def print_board(self): print(self.board[0])
类tictactoe中函数print\u board的父范围是类tictactoe所在的位置,而不是tictactoe所在的位置
board
是一个类变量。将类名(我所做的)或self
放在它前面以引用它。请参阅this以了解差异您应该在类函数中使用
self.board
:类tictactoe中函数print\u board的父范围是类tictactoe所在的位置,而不是tictactoe所在的位置
相关问题 更多 >
编程相关推荐