REPOST: Re: cmp

Mark McEahern markjunk at
Thu Dec 27 17:21:33 CET 2001

> Perhaps then could someone explain to me how one compares classes
> useing the == operator, or indeed if this bad programming practice.

By overloading the __cmp__ method.  Don't confuse the return value of
__cmp__ with whether or not the result of the comparison is that the two
instances being compared are equal.  Examine this sample and note that
__cmp__ isn't merely used to determine equality.  It is also used to
determine sort order.

class foo:

    def __init__(self, bar): = bar

    def __cmp__(self, other):
        if ==
            return 0
        elif <
            return -1
            return 1

    def __repr__(self):
        return "<foo bar='%s'/>" %

a = foo(1)
b = foo(2)
c = foo(3)
d = foo(1)

list = [b, c, a]

print "before sorting:"
print list


print "after sorting:"
print list

print "a == d: %s" % (a == d)

========= WAS CANCELLED BY =======:
From: "Mark McEahern" <markjunk at>
Newsgroups: comp.lang.python
Subject: cmsg cancel <hUHW7.7906$dG.3286832 at>
Control: cancel <hUHW7.7906$dG.3286832 at>
Date: Mon, 31 Dec 2001 01:35:07 GMT
Organization: A poorly-installed InterNetNews site
Lines: 2
Message-ID: <cancel.hUHW7.7906$dG.3286832 at>
X-Trace: 1009775718 27193 (31 Dec 2001 05:15:18 GMT)
X-Complaints-To: usenet at
NNTP-Posting-Date: Mon, 31 Dec 2001 05:15:18 +0000 (UTC)
X-No-Archive: yes
X-Unac4ncel: yes
X-Commentary: I love NewsAgent 1.10 and the Sandblaster Cancel Engine Build 74 (19 March 1999)

This message was cancelled from within Mozilla.

More information about the Python-list mailing list