I’ve been mucking around with class special methods to overload numeric operators via object.__add__(self,other) etc.
Is there a generic way to find out which binary operator was called though?
For unary operators you can use __getattr__, e.g:
class Test():
def __getattr__(self, name):
print name
t = Test()
~t # prints __invert__
but calling binary operators e.g. t+t or t+5 always calls __coerce__ which looses the info about what the operator is.
Solution based on Jochen Ritzel’s answer below: the easiest way is to add the following to the above class:
def __coerce__(self, other):
self.other = other # store 'other' somewhere we can access it
return None
Then __getattr__ (which gets called after __coerce__) has got access to both the operands – as self and self.other– and the operation – as name.
HOWEVER it turns out trying to use dynamic dispatch via __getattr__ is almost certainly a really bad idea compared to just defining the special methods you actually need, as for operators (as opposed to attributes) Python will actually call whatever __getattr__ returns.
(Hope updating my question is ok, didn’t seem to fit in the comment box)
t+tcalls__coerce__and then__add__.__coerce__is supposed to convert (numeric) types to a common class, for example1.0 + 2first coerces both numbers to floats.If you want to do something special you can return proxy objects from
__coerce__that see the following operator.