我在函数中打印数组时遇到问题

2024-06-11 19:03:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在为我的学校项目做一个游戏。我正在使用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])

Tags: 项目函数selfboard游戏元素def学校
2条回答

board是一个类变量。将类名(我所做的)或self放在它前面以引用它。请参阅this以了解差异

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

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所在的位置

相关问题 更多 >