57

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.

Josh Gibson
  • 21,808
  • 28
  • 67
  • 63
  • 4
    @tzot in a way, you're looking at the F'ing M. ;-) – Bob Stein Apr 02 '16 at 09:24
  • Do you imply that Josh is one of Python's manual writers? Sorry, I don't seem to understand what you mean, @BobStein-VisiBone . – tzot Apr 02 '16 at 21:17
  • 15
    @tzot I meant that Stack Overflow **is**, in large part, **The Manual** on Python. It was easier to find this page than [the one at docs.python.org](https://docs.python.org/library/operator.html). Especially if you don't already know to search for `__iadd__` or the term "in-place" addition. – Bob Stein Apr 03 '16 at 00:43

1 Answers1

106

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

mipadi
  • 398,885
  • 90
  • 523
  • 479
  • 3
    +1: Quote the documentation :-) – S.Lott Apr 08 '09 at 11:03
  • Do the types have to match? I.e., can I += two different types together if I want to? I keep getting exceptions, not sure if it's cause I'm doing it wrong or because it's not allowed ever. Docs are very weak on this. – grego Mar 21 '20 at 03:38