Class Variable Access and Assignment

Magnus Lycka lycka at carmen.se
Thu Nov 3 09:55:10 EST 2005


Antoon Pardon wrote:
> There is no instance variable at that point. How can it add 2, to
> something that doesn't exist at the moment.

Because 'a += 1' is only a shorthand for 'a = a + 1' if a is an
immutable object? Anyway, the behaviour is well documented.

http://docs.python.org/ref/augassign.html says:

An augmented assignment expression like x += 1 can be rewritten as x = x 
+ 1 to achieve a similar, but not exactly equal effect. In the augmented 
version, x is only evaluated once. Also, when possible, the actual 
operation is performed in-place, meaning that rather than creating a new 
object and assigning that to the target, the old object is modified instead.

...

For targets which are attribute references, the initial value is 
retrieved with a getattr() and the result is assigned with a setattr(). 
Notice that the two methods do not necessarily refer to the same 
variable. When getattr() refers to a class variable, setattr() still 
writes to an instance variable. For example:

class A:
     x = 3    # class variable
a = A()
a.x += 1     # writes a.x as 4 leaving A.x as 3



More information about the Python-list mailing list