numeric emulation and the rich comparison operators

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Fri Jul 11 11:24:03 CEST 2008


En Thu, 10 Jul 2008 17:37:42 -0300, Ethan Furman <ethan at stoneleaf.us>  
escribi�:

> Greetings, List!
>
> Still working on my Measure class, and my next question is... (drum roll  
> please ;)
>
> What are the advantages of using __[eq|ne|lt|gt|le|ge]__ vs __cmp__?

If your objects obey the trichotomy law (an object MUST BE less than,  
greater than, or equal to another one, and there is no other possibility)  
then __cmp__ is enough, and easier to define than all the rich comparison  
operations.
In other cases, __cmp__ is not suitable: by example, complex numbers can't  
define "greater than" [in a way that preserves the meaning for real  
numbers]; you can only use "equal" or "not equal". You can't use __cmp__  
for this, because it *has* to return either >0 or <0 (implying "greater  
than" or "less than"). In this case it's best to use the rich comparison  
operators: define __eq__ and __ne__ and make all other comparisons between  
complex numbers raise an exception.

-- 
Gabriel Genellina




More information about the Python-list mailing list