Global variables from a class

Piet van Oostrum piet at cs.uu.nl
Fri May 29 05:58:33 EDT 2009


>>>>> Kless <jonas.esp at googlemail.com> (K) wrote:

>K> I usually use a class to access to global variables. So, which would
>K> be the correct way to set them --since the following classes--:

>K> --------------------
>K> class Foo:
>K>    var = 'lala'

>K> class Bar:
>K>    def __init__(self):
>K>       self.var = 'lele'
>K> --------------------

>K> Or is it the same?

I don't see any global variable in your code. 
var is a class variable (attribute) in Foo, whereas in Bar var is an
instance variable (attribute). These are two different things. However a
class variable acts as a kind of default for an instance variable. If
all your instances have the same value for var, Foo is a good way to
accomplish this. If they are all different, the Bar is the way to go.

You can also mix them if several of the instances use the same value
'lala' but some need 'lele' or sometime later in the life of the instance
the value will be changed to 'lele'

class Bletch:
    var = 'lala'

    def update(self):
        self.var = 'lele'

In this case it is a matter of taste whether you use the Foo or the Bar
way.

-- 
Piet van Oostrum <piet at cs.uu.nl>
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org



More information about the Python-list mailing list