Beginners question

Rhodri James rhodri at wildebst.demon.co.uk
Sat Jul 18 09:17:12 EDT 2009


On Sat, 18 Jul 2009 03:03:32 +0100, gabrielmonnerat  
<gabrielmonnerat at gmail.com> wrote:

> Ronn Ross wrote:
>> How do you define a global variable in a class. I tried this with do  
>> success:
>> class ClassName:
>>     global_var = 1
>>        def some_methos():
>>         print global_var
>>
>> This doesn't work. What am I doing wrong?
> You need pass "self" to the function and "global_var" needs be called  
> with self.
>
> class ClassName:
>     global_var = 1
>        def some_methos(self):
>         print self.global_var

If the OP really wants global_var to be global to the class, this
approach will only work as long as he never assigns to self.global_var.

The terminology is a bit confusing here.  "Global variables" refers to
variables which are global to an entire module, ones that you would
use "global" to declare inside a function.  Something like this:

x = 5
def set_x(y):
     global x
     x = y

set_x(3)
print x

...gives the result "3"

The idea of defining a global variable in a class is a bit of a
nonsense, since globals exist for the entire module.  There are,
however, variables that exist and are the same for every instance
of a class, or "class attributes" as they are normally called.  You
use them either by assignment in the class definition, or in a
method by prefixing them with the class name.

class ClassName:
     global_var = 1
     def some_method(self):
         print ClassName.global_var
         ClassName.global_var = 2

"Instance attributes", the ones prefixed by "self", are what get
used for most purposes.  These are separate for each different
instance of the class.

class ClassName:
     def __init__(self, val):
        self.var = val

a = ClassName(1)
b = ClassName(2)

print a.var, b.var

...gives the result "1 2"

The wrinkle is that if you read from an instance attribute that
doesn't exist, Python will use a class attribute of the same name
if there is one.  This is often exploited for setting default
values.  Beware, though: the moment you assign, an instance
attribute is created -- the underlying class attribute is *not*
changed.

class ClassName:
     global_var = 1
     def some_method(self):
         self.global_var = 2

a = ClassName()
b = ClassName()
b.some_method()
print a.global_var, b.global_var

...gives the result "1 2" again!

-- 
Rhodri James *-* Wildebeest Herder to the Masses



More information about the Python-list mailing list