From Dive into Python:
Class attributes are available both through direct reference to the
class and through any instance of the class.Class attributes can be used as class-level constants, but they are
not really constants. You can also change them.
So I type this into IDLE:
IDLE 2.6.5
>>> class c:
counter=0
>>> c
<class __main__.c at 0xb64cb1dc>
>>> v=c()
>>> v.__class__
<class __main__.c at 0xb64cb1dc>
>>> v.counter += 1
>>> v.counter
1
>>> c.counter
0
>>>
So what am I doing wrong? Why is the class variable not maintaining its value both through direct reference to the class and through any instance of the class.
Because ints are immutable in python
rebinds
v.counterto a new int object. The rebinding creates an instance attribute that masks the class attributeYou can see this happening if you look at the
id()ofv.counterHere you can see that
vnow has a new attribute in its__dict__Contrast the case where
counteris mutable, eg alist