[Tutor] class question
alan.gauld at blueyonder.co.uk
Tue May 18 19:13:00 EDT 2004
> class test:
> def __init__(self):
> def somedef(self):
> 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
x = 42
def setX(self,value): self.x = value
# create two instances
a = C()
b = C()
# now set the a instance x to a new value
> 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...
More information about the Tutor