如何在不同 class __init__ 中的实例上调用 class 方法

How can I call a class method on an instance within a different class __init__

我正在 python 中创建一个井字游戏。我试图在我的 class class init 中的 boardState 对象上从我的 Board class 调用更新方法 class。 当我 运行 我得到 NameError: name boardState is not defined.


class Board:
    def __init__(self, player1 =  "player1", player2 = "player2"):
        self.p1 = player1
        self.p2 = player2
        self.matrix = MATRIX
        self.winner = 'none'
        self.available = getAvailable(self.matrix)
        
    def update(self):
        clear()
        getAvailable(self.matrix)
        self.show()

class Turn:
        def __init__(self, sym):
            self.sym = sym
            boardState.update()
            terminalState(boardState, self.sym, available)
            print(f"{self.sym}'s turn:")

def main():
    boardState = Board()
    altTurns()

你收到这个错误表明你在引用它之前没有定义“boardState”,

使用前需要设置为新的Board Object

class Board:
    def __init__(self, player1 =  "player1", player2 = "player2"):
        self.p1 = player1
        self.p2 = player2
        self.matrix = MATRIX
        self.winner = 'none'
        self.available = getAvailable(self.matrix)
        
    def update(self):
        clear()
        getAvailable(self.matrix)
        self.show()

class Turn:
        def __init__(self, sym):
            self.sym = sym
            boardState = Board() #the line I added
            boardState.update()
            terminalState(boardState, self.sym, available)
            print(f"{self.sym}'s turn:")

这应该可以解决您的问题

如果您希望 Turn 对象可以访问您在 main() 中创建的 boardState 对象(并且 main 又可以访问更新后的 boardState),您应该将其作为参数传递给所有相关函数访问它。

我假设 Turn 是由 altTurns 创建的,所以 altTurns 本身应该有一个板对象,它可以用来创建初始的 Turn

class Turn:
        def __init__(self, sym, boardState):
            self.sym = sym
            boardState.update()
            terminalState(boardState, self.sym, available)
            print(f"{self.sym}'s turn:")

def altTurns(boardState):
    sym = None  # or something?
    turn = Turn(sym, boardState)
    # more turns happen?

def main():
    boardState = Board()
    altTurns(boardState)
    # our boardState has now been updated by Turn()