Skip to content
Advertisement

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

I am creating a tic-tac-toe game in python. I’m trying to call the update method from my Board class on my boardState object within the class init of my Turn class. When I run it I get 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()

Advertisement

Answer

you are getting this error siense you haven’t defined “boardState” before referencing it,

you need to set it to be a new Board Object before using it

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:")

this should fix your problem

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement