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]
pinside of the Game class definition. You probably need to move that to Game's__init__method.gamedoes not exist when the interpreter is creatingPlayer. You have a bit of a conundrum, each class has a reference to the other but because Python creates the objects sequentially, one will always not exist no matter how you rearrange the definitions. You need to re-think the design.