views:

808

answers:

3

Is it possible to override += in Python?

+16  A: 

Yes, override the __iadd__ method. Example:

def __iadd__(self, other):
    self.number += other.number
    return self
John Kugelman
Thank you very much, John. I appreciate the help.
Evan Fosmark
You shouldn't implement `__iadd__` if your class represents immutable objects. In that case just implement `__add__` which will be used to override `+=` instead. For example you can use `+=` on immutable types such as strings and integers, which couldn't be done using `__iadd__`.
Scott Griffiths
+4  A: 

http://docs.python.org/reference/datamodel.html#emulating-numeric-types

For instance, to execute the statement x += y, where x is an instance of a class that has an __iadd__() method, x.__iadd__(y) is called.

Unknown
+5  A: 

In addition to overloading __iadd__ (remember to return self!), you can also fallback on __add__, as x += y will work like x = x + y. (This is one of the pitfalls of the += operator.)

>>> class A(object):
...   def __init__(self, x):
...     self.x = x
...   def __add__(self, other):
...     return A(self.x + other.x)
>>> a = A(42)
>>> b = A(3)
>>> print a.x, b.x
42 3
>>> old_id = id(a)
>>> a += b
>>> print a.x
45
>>> print old_id == id(a)
False

It even trips up experts:

class Resource(object):
  class_counter = 0
  def __init__(self):
    self.id = self.class_counter
    self.class_counter += 1

x = Resource()
y = Resource()

What values do you expect x.id, y.id, and Resource.class_counter to have?

Roger Pate
Your second example has nothing to do with iadd or +=. The same result occurs if you use self.class_counter = self.class_counter + 1It's just a scoping issue, using self when Resource should be used.
FogleBird
It's an example of how using += can lead to problems. If you're overloading __iadd__, then you're opening users of your class (including yourself) to this, and, at the very least, you should know the issue exists beforehand.
Roger Pate