class Number(object):
def __init__(self):
super(Number, self).__init__()
self.data = 10
def __getattr__(self, name):
def _missing(*args, **kwargs):
method = getattr(self.data, name)
return method(args[0])
return _missing
a = Number()
b = Number()
print a.__add__(10) # this is ok!
print a + 10 # TypeError: "unsupported operand type(s) for +: 'Number' and 'int'"
print a + b # TypeError: "unsupported operand type(s) for +: 'Number' and 'Number'"
Question:
What’s the difference between “a.__add__(10)” and “a + 10”, How can I hook the operator “+” ?
Python will only use an actual
__add__method, not one that only “exists” due to__getattr__.When adding
__add__ = (10).__add__it works fine.So what you’ll want to do is adding proxy methods: