Static variable vs Class variable
Diez B. Roggisch
deets at nospam.web.de
Tue Oct 9 13:23:37 EDT 2007
> In point #3, you really bind a name to a value. As you probably know, in
> Python, there are names and objects. The initial value of the name 'a'
> is 1. It is an immutable object. The "+=" operator usually increments a
> value of an object. However, because the 'int' type is immutable, the +=
> operator will rather rebind this variable to a newly created value. I
> believe this is what is happening here.
Your believes aside, this is simply wrong. The statement
a += x
always leads to a rebinding of a to the result of the operation +. I
presume you got confused by the somewhat arbitrary difference between
__add__
and
__iadd__
that somehow suggest there is an in-place-modification going on in case
of mutables.
but as the following snippet shows - that's not the case:
class Foo(object):
def __add__(self, o):
return "__add__"
def __iadd__(self, o):
return "__iadd__"
a = Foo()
a += 1
print a
a = Foo()
b = Foo()
c = a + b
print c
So you see, the first += overrides a with the returned value of __iadd__.
The reason for the difference though is most probably what you yourself
expected: thus it's possible to alter a mutable in place.
Diez
More information about the Python-list
mailing list