Which class's comparison function is called?

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Tue Jun 5 23:20:36 EDT 2007


On Tue, 05 Jun 2007 19:16:53 -0700, Bill Jackson wrote:

[snip]

>  From the above, it seems that Python always uses the function defined
> by the class on the LEFT.  However, I don't understand the following
> then:

[snip]

In general, infix operators like + - * etc. will call the appropriate 
methods __add__ __sub__ etc. for the class on the LEFT. If the class on 
the left doesn't define such a method, the class on the right will be 
called with __radd__ __rsub__ etc. 

(There are complications -- see here for details: 
http://docs.python.org/ref/numeric-types.html )

The rules for comparison functions are a little more complicated, and by 
a little I mean a lot. You can start here:

http://docs.python.org/ref/customization.html


The exception to the "try the left operand first, then try the right 
operand" rule happens when the left operand is a built-in like int, 
float, etc. In that case, if Python called int.__add__ (or whatever the 
method was), your class would likely never be called, which makes it hard 
for you to over-ride the operator. So Python calls your methods first.

And don't forget that if you are inheriting from object, object will 
likely define default rich comparisons that probably don't do what you 
expect.




-- 
Steven.



More information about the Python-list mailing list