Is it possible to change the default __add__ method to do something else than just add?
For example, if the goal is with this line:
5+5 get The answer is 10 or anything else like 0 by changing __add__ to be x-y instead of x+y?
I know I can change __add__ in my own classes:
class Vec():
def __init__(self,x,y):
self.x = x
self.y = y
def __repr__(self):
return f'{self.x, self.y}'
def __add__(self, other):
self.x += other.x
self.y += other.y
return Vec(self.x,self.y)
v1 = Vec(1,2)
v2 = Vec(5,3)
v1+v2
# (6, 5)
Can I somehow target the default __add__ method to change its behaviour? I intuitively think that __add__ is defined in each default data type to return specific results, but then again, the __add__ method is what we address when changing it for a specific class, so, is it possible to change the main __add__ logic?
Something along these lines?
class __add__():
...
object.__add__isn't defined, so effectively nearly every standard class that supports addition defines it from scratch.__add__method to do something different. Change behaviour for built-in types: No, at least not without recompiling python after changing the C source code.x << yintaddition here, that oflistaddition here, tuple addition here, etc.