[Tutor] class question

Alan Gauld alan.gauld at blueyonder.co.uk
Tue May 18 19:13:00 EDT 2004

> class test:
>     a=1
>     b=2
>     def  __init__(self):
>       self.c=5
>       self.e=6
>     def somedef(self):
>       self.f=7
>       self.g=8
> The self.a=2 tags this variable to the genrated instance via self
> ok  ... and appears to be a global variable.

No its local (bound) to the particular instance. You cannot access 'a'
without using the object reference

> So what happens with plain a=2.

That applies at the class level. That is all instances of the class
share the same value for 'a', unless they overwrite it locally:

# define a class
class C:
   x = 42
   def setX(self,value): self.x = value

# create two instances
a = C()
b = C()

print 'a.x=',a.x
print 'b.x=',b.x

# now set the a instance x to a new value
print 'a.x=',a.x
print 'b.x=',b.x

> What I am asking is when sould I use a=2 & when self.a=2 ?

Use class variables when you want to set a value shared by all
instances. For example you might store the maximum size of data
the class can handle (might be limited by OS constraints say).

Or if it were a game, the class could hold the number of lives
allowed. An instance variable could hold the number of lives left.
All insatances share the limit but each instance has its own
idea of how many lives it has left. The class value in turn
might depend on the skill level being used by the player etc...


Alan G.

More information about the Tutor mailing list