I have a vector class:
class Vector: 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+n.x, self.y+n.y) which works fine, i.e. I can write:
a = Vector(1,2) print(a + 1) # prints (2,3) However if the order of operation is reversed, then it fails:
a = Vector(1,2) print(1 + a) # raises TypeError: unsupported operand type(s) # for +: 'int' and 'instance' I understand the error: the addition of an int object to an Vector object is undefined because I haven't defined it in the int class. Is there a way to work around this without defining it in the int (or parent of int) class?