[Tutor] class variables

Alan Gauld alan.gauld at blueyonder.co.uk
Thu Jun 24 03:14:28 EDT 2004

> class beer:
>     def __init__(self):
>        self.make = 'murphys'
>        cans = 4
> There's several examples I've seen where 'self.var' isn't used, just
> 'var' is, as in 'cans' above.
> I know that each instance of 'beer' will have its own value for
> but what is the use of 'cans' without using self ?

Its just a local variable inside the init function. Just like any
local variable it will go out of scope and be garbage collected when
init terminates.

However if the variable is declared outside of a method it is a class
variable (see a previous thread - last month mebbe?) and is shared
all instances:

class C:
   shared = 42
   def __init__(s,v):
     self.inst = v

a = C(24)
b = C(12)

print a.shared, a.inst   # -> 42,24
print b.shared,b.inst    # -> 42,12


Alan G
Author of the Learn to Program web tutor

More information about the Tutor mailing list