Global variables from a class
Jean-Michel Pichavant
jeanmichel at sequans.com
Fri May 29 08:55:34 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?
>
This form is the most suited for what your doing:
> class Foo:
> var = 'lala'
It is a good practice to place your globals into a class (making them non global by the way). It helps also writing good documentation in docstrings.
I would add:
> class Foo:
> """Hold the secrets of eternity"""
> var = 'lala'
> """One variable"""
> ANY_CONSTANT = 14
> """The universal answer to all questions"""
Having strong naming convention also helps a lot.
Jean-Michel
PS: FYI, in the second form, var is an instance variable, and you need to create an instance to access it => Bar().var while Foo.var is enough for the first form.
More information about the Python-list
mailing list