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]