Using __add__ operator with multiple arguments in Python

No, you can’t use multiple arguments. Python executes each + operator separately, the two + operators are distinct expressions.

For your example, object + 1 + 2 really is (object + 1) + 2. If (object + 1) produces an object that has an __add__ method, then Python will call that method for the second operator.

You could, for example, return another instance of A here:

>>> class A:
...     def __init__(self, val):
...         self.val = val
...     def __repr__(self):
...         return f'<A({self.val})>'
...     def __add__(self, other):
...         print(f'Summing {self} + {other}')
...         return A(self.val + other)
...
>>> A(42) + 10
Summing A(42) + 10
<A(52)>
>>> A(42) + 10 + 100
Summing A(42) + 10
Summing A(52) + 100
<A(152)>

Leave a Comment