PYTHON TypeError: validTicTacToe() missing 1 required positional argument: 'board'

PYTHON TypeError: validTicTacToe() missing 1 required positional argument: 'board'

我是 python 的新手,正在尝试 运行 VScode 上的此代码。它给出了一个错误提示 TypeError: validTicTacToe() missing 1 required positional argument: 'board'。我在这里做错了什么? 我实际上是想了解 self 是如何工作的。我知道 c++ 所以如果你能解释一下与 c++ 的比较,那将很有帮助。

此外,这是一个 leetcode 问题,它在 leetcode 上运行良好,但看起来我必须在 运行 将其应用于 VScode 之前进行一些更改。 TIA

def validTicTacToe(self, board) -> bool:
    X, O = self.countSymbols(board)
    if O > X:
        # Os can't  be greater than Xs
        return False
    elif abs(X-O) > 1:
        # Difference can only be 1
        return False
    elif X > O:
        # X can't have more moves than O if O is already won
        if self.checkTriads(board, 'O'): return False
    else:
        # X and O can't have equal moves if X is winning
        if self.checkTriads(board, 'X'): return False
    return True


def countSymbols(self, board):
    X = 0
    O = 0
    for row in board:
        for i in row:
            if i == 'X':
                X+=1
            elif i == 'O':
                O+=1
    return X,O
                    
def checkTriads(self, board, sym='X'):
    # Checking for Hight triads
    i = 0
    while i<3:
        if (board[0][i] == board[1][i] == board[2][i] == sym):
            return True
        i+=1
            
    # Checking for width
    i=0
    while i<3:
        if (board[i][0] == board[i][1] == board[i][2] == sym):
            return True
        i+=1
            
    # Checking for diag.
    if (board[0][0] == board[1][1] == board[2][2] == sym):
            return True
    if (board[0][2] == board[1][1] == board[2][0] == sym):
            return True
    return False

board=["O  ","   ","   "]
validTicTacToe(board)```

您以对象方法的方式定义了函数。这些将始终自动接收其实例对象作为第一个参数。按照惯例,这个参数被命名为self。但是,您没有声明 class 来包含这些方法。您可以从函数中删除 self 参数或将它们包装在 class 定义中:

class TicTacToe():
    def validTicTacToe(self, board) -> bool:
        # ...

game = TicTacToe()
board = ["O  ", "   ", "   "]
game.validTicTacToe(board)

要实际使用 class 机制,面板应该是 属性:

class TicTacToe():
    def __init__(self, board):
        self.board = board

    def validTicTacToe(self) -> bool:
        # now you can use self.board instead of passing it around

board = ["O  ", "   ", "   "]
game = TicTacToe(board)
game.validTicTacToe()