Global in multiple files
laurent.pointal at wanadoo.fr
Tue Jun 12 21:45:18 CEST 2001
[posted and mailed]
arturs at iidea.pl (Artur Skura) wrote in
news:slrn9i6mb8.1vb.arturs at aph.waw.pdi.net:
> I'm not a fan of OO but I decided to give it a try. After all, Python
> makes it elegant.
> So I wrote a program usuing classes, methods etc. All nice. Then it
> grew up and I decided to split it in several files - one class into
> each class as Guido asked us to do.
> And then, I came across my first problem: I had had a global variable
> (just one!) and it wouldn't work anymore. At all. Any 'global'
> declarations wouldn't help, and without it I'm lost.
> So, I thought I might be smarter than it. I would pass this
> variable to where I need it, but... it stil obstinately refuses to
> work. But then, my ex-global is a list of instances of a class,
> and methods in instances of another class won't accept it as
> an argument.
If you split class AClass in module A and class BClass in module B, and need
to access a global globlist:
Put globlist in A as a global.
In A access globlist directly as a global.
In B do an "import A".
In B access globlist via "A.globlist".
Or you can:
Put globlist in a tierce G module.
In A and B do n "import G"
In A and B access globlist via "G.globlist"
(second solution can solve cross reference between several modules by moving
shared references into one common place, and it has the advantage to use the
same access method for everybody)
The use of module.name syntax ensure that everybody will use the same
global, even if it the referenced object is changed. To enforce this rule
you can prefix the global by an _ so that it cannot be imported directly.
Finally you can:
Define a module with accessor functions (or accessor classe methods), which
will be used to manipulate the global.
More information about the Python-list