【问题标题】:I have issues with printing out the array in a function我在函数中打印出数组时遇到问题
【发布时间】:2019-06-16 05:50:06
【问题描述】:

我正在尝试为我的学校项目制作一个tictactoe 游戏。我正在使用 pycharm,并且不知何故在 print_board 函数中,我在 board[0] 下得到了红线。似乎它无法获取函数内部的板元素。如何在 print_board 函数中打印板子元素?

class tictactoe:

    board = [0, 1, 2,
             3, 4, 5,
             6, 7, 8]

    def print_board(self):
        print(board[0])

【问题讨论】:

  • 这是在class 中吗?哪里出错了?
  • 是的,这是在课堂上

标签: python


【解决方案1】:

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()

【讨论】:

  • 现在我在打印 print_board() 函数时遇到问题,错误:print_board() 缺少 1 个必需的位置参数:'self'
  • @stressedoutnut 我测试了这段代码,它可以工作......你用t.print_board()调用它吗?
【解决方案2】:

你应该在类函数中使用self.board

class tictactoe:

    board = [0, 1, 2,
        3, 4, 5,
        6, 7, 8]

    def print_board(self):
        print(self.board[0])

tictactoe 类中 print_board 函数的父范围是 tictactoe 类所在的位置,而不是 tictactoe。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-13
    • 1970-01-01
    • 1970-01-01
    • 2021-10-13
    • 2021-02-08
    • 1970-01-01
    • 2016-06-25
    • 1970-01-01
    相关资源
    最近更新 更多