Retrieve binary operator called on an instance
<p>I've been mucking around with class special methods to <a href="http://docs.python.org/release/2.6.7/reference/datamodel.html#emulating-numeric-types" rel="nofollow">overload numeric operators</a> via <code>object.__add__(self,other)</code> etc.</p>

<p>Is there a <em>generic</em> way to find out which binary operator was called though?</p>

<p>For unary operators you can use <code>__getattr__</code>, e.g:</p>

<pre><code>class Test():
  def __getattr__(self, name):
    print name
t = Test()
~t  # prints __invert__
</code></pre>

<p>but calling binary operators e.g. <code>t+t</code> or <code>t+5</code> always calls <code>__coerce__</code> which looses the info about what the operator is.</p>

<hr>

<p>Solution based on Jochen Ritzel's answer below: the easiest way is to add the following to the above class:</p>

<pre><code>def __coerce__(self, other):
  self.other = other    # store 'other' somewhere we can access it
  return None
</code></pre>

<p>Then <code>__getattr__</code> (which gets called after <code>__coerce__</code>) has got access to both the operands - as <code>self</code> and <code>self.other</code>- and the operation - as <code>name</code>.</p>

<p>HOWEVER it turns out trying to use dynamic dispatch via <code>__getattr__</code> is almost certainly a <em>really</em> bad idea compared to just defining the special methods you actually need, as for operators (as opposed to attributes) Python will actually call whatever <code>__getattr__</code> returns.</p>

<p>(Hope updating my question is ok, didn't seem to fit in the comment box)</p>
