Accessing variables created after import in imported files

Don O'Donnell donod at home.com
Tue Jan 2 03:18:08 EST 2001


Hi Jesse,

I think you would have a better design if you passed the Game instance
as a parameter to the ThingThatUsesGame constructor.  It seems to make
sense (to me anyway) that you would want to tell the ThingThatUsesGame
which game he's using. Of course, I'm not familiar with your application
so there may be other issues that require you to use a global, but, in 
general, globals should be avoided when ever possible.

class ThingThatUsesGame:
    def __init__(self, game):
        self.game = game
        print self.game.foo

gameX = Game()
gameUserX = ThingThatUsesGame(gameX)

# or, if you don't need to refer to the game instance anywhere else:

gameUserX = ThingThatUsesGame(Game())

This design will also allow you to have multiple users playing 
different games.

- Don

Jesse W wrote:
> 
> Sorry about the somewhat unclear subject line.  I am not totally sure
> of the general form of my problem, so it is hard to write it as a
> subject line.  My problem involves a program I am writting to allow
> people to play a really fun card game I know, Hot Death Uno.  Insted of
> posting the actual code(It's really long, and even snipits would be
> pretty complex) I have enclosed code which demostrates the problem, but
> is not the actual code I am working with.  If someone want's to see it,
> I would be glad to e-mail it to them.
>         The code is in two files:
> #file 1
> import file2
> 
> class Game:
>     def __init__(self):
>         global TheGame
>         TheGame=self
>         #this lets other classes access the current
>         #instence of the game without knowing the name it was
>         #created as.
>         self.foo='Some random variable'
> x=Game()
> foo=file2.ThingThatUsesGameClass()
> 
> #file 2
> import file1
> 
> class ThingThatUsesGameClass:
>     def __init__(self):
>         print TheGame.foo #this should use the instance of the Game     #class
> created in the other file.
> 
>                 Thank you very much for your time,
>                                         Jesse Weinstein



More information about the Python-list mailing list