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

Time:05-29

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

CodePudding user response:

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

CodePudding user response:

If you want your Turn object to have access to the boardState object you've created in main() (and for main in turn to have access to the updated boardState), you should pass it in as a parameter to give all of the relevant functions access to it.

I assume the Turn is created by altTurns, so altTurns should itself take a board object that it can use to create the initial 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()
  • Related