views:

375

answers:

1

I know about the __add__ method to override plus, but when I use that to override +=, I end up with one of two problems:

(1) if __add__ mutates self, then

z = x + y

will mutate x when I don't really want x to be mutated there.

(2) if __add__ returns a new object, then

tmp = z
z += x
z += y
tmp += w
return z

will return something without w since z and tmp point to different objects after z += x is executed.

I can make some sort of .append() method, but I'd prefer to overload += if it is possible.

+20  A: 

Yes. Just override the object's __iadd__ method, which takes the same parameters as add. You can find more information here.

mipadi
It's `__iadd__` actually, not `__addi__`.
DNS
+1: Quote the documentation :-)
S.Lott