Separating __cmp__ from < and > ?

Erik Max Francis max at alcyone.com
Mon Aug 14 21:26:26 EDT 2000


Huaiyu Zhu wrote:

> In many situations it is conceptually possible to have a!=b without
> either
> a<b or a>b.  Mathematically, this is the case for objects that live in
> a
> partially ordered space.

I've encountered this as well.

> For example, I want all the following to be false (not really on lists
> but
> on user defined classes of similar nature)
> 
> [1,2] == [2,1]
> [1,2] < [2,1]
> [1,2] > [2,1]
> 
> Is it possible to simulate this in Python?

Is it imperative that they return false for inequalities?

In my case, I had a class which encapsulated (essentially) an ordered
pair, which sounds like a similar situation to yours.  I wanted to test
for equality and inequality, but inequalities have little meaning.  So I
simply defined a __cmp__ method that does something meaningful on
equalities and inequalities, and does something arbitrary on
inequalities.  In this case it was simple running cmp on tuples
constructed from the two coordinates:

    def __cmp__(self, other):
        """Not very meaningful for inequalities."""
        return cmp(self.tuple(), other.tuple())

-- 
 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE
/  \ The critical period in matrimony is breakfast-time.
\__/ A.P. Herbert
    Polly Wanna Cracka? / http://www.pollywannacracka.com/
 The Internet resource for interracial relationships.



More information about the Python-list mailing list