You need to also define __radd__
Some operations do not necessarily evaluate to a + b == b + a and why Python defines add and radd methods .
Explaining himself better: he supports the fact that "int" does not define a + operation with class Vector instances as part of the operation. Therefore, the vector + 1 does not coincide with the vector 1 +.
When Python tries to see what method 1.__add__ can do, an exception is thrown. And Python goes and searches for a Vector.__radd__ operation to try to complete it.
In the case of OP, the estimate is true and has the value __radd__ = __add__
class Vector(object): def __init__(self, x, y): self.x, self.y = x, y def __str__(self): return '(%s,%s)' % (self.x, self.y) def __add__(self, n): if isinstance(n, (int, long, float)): return Vector(self.x+n, self.y+n) elif isinstance(n, Vector): return Vector(self.x+nx, self.y+ny) __radd__ = __add__ a = Vector(1, 2) print(1 + a)
What outputs:
(2,3)
The same applies to all numerical operations.
source share