[python] What exactly does += do in python?

I need to know what += does in Python. It's that simple. I also would appreciate links to definitions of other shorthand tools in Python.

This question is related to python operators notation shorthand compound-assignment

The answer is

In Python, += is sugar coating for the __iadd__ special method, or __add__ or __radd__ if __iadd__ isn't present. The __iadd__ method of a class can do anything it wants. The list object implements it and uses it to iterate over an iterable object appending each element to itself in the same way that the list's extend method does.

Here's a simple custom class that implements the __iadd__ special method. You initialize the object with an int, then can use the += operator to add a number. I've added a print statement in __iadd__ to show that it gets called. Also, __iadd__ is expected to return an object, so I returned the addition of itself plus the other number which makes sense in this case.

>>> class Adder(object):
        def __init__(self, num=0):
            self.num = num

        def __iadd__(self, other):
            print 'in __iadd__', other
            self.num = self.num + other
            return self.num

>>> a = Adder(2)
>>> a += 3
in __iadd__ 3
>>> a

Hope this helps.

Similar questions with python tag:

Similar questions with operators tag:

Similar questions with notation tag:

Similar questions with shorthand tag:

Similar questions with compound-assignment tag: