Which class's comparison function is called?

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Wed Jun 6 05:20:36 CEST 2007

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


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


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:


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 


More information about the Python-list mailing list