Static variable vs Class variable

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Tue Oct 9 14:08:34 EDT 2007


On Tue, 09 Oct 2007 19:23:37 +0200, Diez B. Roggisch wrote:

> Your believes aside, this is simply wrong. The statement
> 
> a += x
> 
> always leads to a rebinding of a to the result of the operation +.

Not true.

>>> L = []
>>> id(L)
3083496716L
>>> L += [1]
>>> id(L)
3083496716L

It's the same L, not rebound at all.



> 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.

The __iFOO__ methods are supposed to do in-place modification if 
possible, but it is up to the class writer to make them do so. In the 
case of your example, you specifically created an __iadd__ method that 
didn't even attempt in-place modification. What did you expect it to do?


> 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__.

That's because you told it to do that. If you told it to do something 
more sensible, it would have done so. Lists know how to do in-place 
modification:

>>> id(L)  # from above
3083496716L
>>> L *= 5
>>> id(L)
3083496716L
>>> L = L*5
>>> id(L)
3083496972L


-- 
Steven.



More information about the Python-list mailing list