Overloading operators on the rigth.

Alex Martelli aleaxit at yahoo.com
Tue Oct 12 10:06:52 EDT 2004


denis wendum <wendum.denis at pasdepourriels.edf.fr> wrote:

> But my guess to define the method __rlt__ in my class in order to be
> able to evaluate expressions "non_instance < instance" did not work.

Sensible guess, but not the way things work.

> So what are the names (if they exist at all) of the comparison operators
> <,>,== and so on,  when one wants to exend their rigth hand side to a
> user defined (instance of a) class?

Here's how to find out:

>>> class foo:
...   def __getattr__(self, name):
...     print 'looking for %r' % name
...     raise AttributeError, name
... 
>>> f=foo()
>>> 12 < f
looking for '__gt__'
looking for '__coerce__'
looking for '__cmp__'
True
>>> 

See what's happening here?  After determining that int (the type of 12)
cannot deal with comparing 12 with an instance of foo, Python's
implementation of < turns to the right hand side... and asks for a
__gt__ method first!  Makes sense, because 12 < f is presumably going to
be the same thing as f > 12 ... once it doesn't find __gt__ the
implementation continues by trying to coerce f to an int (by checking if
class foo supports __coerce__) and lastly by trying for the old-style
comparison method __cmp__.  But you presumably don't care about that;
rather, the gist of it is: write your __gt__ -- that will also be used
as your "__rlt__" -- and so on!


Alex



More information about the Python-list mailing list