I am trying to overload several operators at once using the __getattr__
function. In my code, if I call foo.__add__(other)
it works as expected, but when I try foo + bar
, it does not. Here is a minimal example:
class Foo():
def add(self, other):
return 1 + other
def sub(self, other):
return 1 - other
def __getattr__(self, name):
stripped = name.strip('_')
if stripped in {'sub', 'add'}:
return getattr(self, stripped)
else:
return
if __name__=='__main__':
bar = Foo()
print(bar.__add__(1)) # works
print(bar + 1) # doesn't work
I realize that it would be easier in this example to just define __add__
and __sub__
, but that is not an option in my case.
Also, as a small side question, if I replace the line:
if stripped in {'sub', 'add'}:
with
if hasattr(self, name):
the code works, but then my iPython kernel crashes. Why does this happen and how could I prevent it?