Reputation: 21
I'm setting up a simple game and am having trouble accessing the Game class instance from the Player class instance:
class Player():
global game
print game.board # NameError: name 'game' is not defined
class Game():
def __init__(self):
self.board = range(9)
p = Player()
if __name__ == "__main__":
game = Game()
I'm sure this is a simple fix/misunderstanding on my part, but what am I missing?
Upvotes: 1
Views: 75
Reputation: 2419
The interpreter will first try to make class Player
, then class Game
and then run the code. So it will make class Player
before game = Game()
is executed and hence there is no variable game
at that moment and cause your error.
Upvotes: 3
Reputation: 53525
A better approach is to use DI (dependency injection) in order to "pass" a Game
object to Player
upon init:
class Player(object):
def __init__(self, game):
self.game = game
def print_player(self):
print self.game.board
class Game(object):
def __init__(self):
self.board = range(9)
if __name__ == "__main__":
game = Game()
player = Player(game)
player.print_player() # prints [0, 1, 2, 3, 4, 5, 6, 7, 8]
Relying on globals()
is not a good practice since it relies on the order of execution (like in your case), makes the code less readable (you have to jump from one place to another instead of reading it "fluently") as well as it might introduce side effects.
Bad practice (a.k.a. don't do it at home!):
The following code (though it's a bad practice) will work since the order of decelerations is meaningful when you're using globals()
: game = Game()
should be declared before class Player
in order for it to be used there:
class Game():
def __init__(self):
self.board = range(9)
game = Game()
class Player():
global game
print game.board
p = Player() # prints [0, 1, 2, 3, 4, 5, 6, 7, 8]
Upvotes: 2