开发者

Retrieve binary operator called on an instance

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 almos开发者_如何学运维t 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+t calls __coerce__ and then __add__. __coerce__ is supposed to convert (numeric) types to a common class, for example 1.0 + 2 first coerces both numbers to floats.

If you want to do something special you can return proxy objects from __coerce__ that see the following operator.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜