Overloading operators on the rigth.

Bengt Richter bokr at oz.net
Wed Oct 13 03:07:35 CEST 2004


On Tue, 12 Oct 2004 16:06:52 +0200, aleaxit at yahoo.com (Alex Martelli) wrote:

>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!
>

On my system, (NT4, python 2.3.2) what really happens for newstyle classes
isn't apparent from that experiment:

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

The old style does work much the same (but note the default end result ;-)
Is that a 2.3.2 bug?

 >>> 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__'
 False

Regards,
Bengt Richter



More information about the Python-list mailing list