Global variables from a class

Dave Angel davea at ieee.org
Fri May 29 09:00:41 EDT 2009


Kless wrote:
> I usually use a class to access to global variables. So, which would
> be the correct way to set them --since the following classes--:
>
> --------------------
> class Foo:
>    var = 'lala'
>
> class Bar:
>    def __init__(self):
>       self.var = 'lele'
> --------------------
>
> Or is it the same?
>
>   
What Python calls global variables are attributes of a module.  So other 
modules can access them by using the module name, eg..  globalModule.var

If you're trying to make them independent of file name, so others can 
access them without knowing what module they are defined in, you can 
create a class Foo approach.  Then somehow (there are several easy ways) 
you get a reference to that class into each module, and they can use 
Foo.var to access the attributes of the class.  You still have a 
reserved name the other modules need to know, it just doesn't have to be 
a module itself.  And if the data is defined in the initial script, it 
avoids the traps that re-importing the script can cause.

If you pass that Foo as a parameter to your functions, you can avoid 
having Foo being a global variable itself, in each module other than the 
first.

But, to the core of the matter, if there's any chance that the value 
might change in the lifetime of the running program, you should probably 
not be using them as globals at all.  This is where the Bar approach 
helps.  Attributes defined in that way are attributes of an instance of 
Bar, and thus there can be more than one such.  The Bar instance can 
frequently allow you to generalize a program which might otherwise be 
hemmed in by globals.  And instead of passing Foo to functions, you pass 
bar_instance






More information about the Python-list mailing list