REPOST: Re: cmp

Mark McEahern markjunk at mceahern.com
Thu Dec 27 11:21:33 EST 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):
        self.bar = bar

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

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

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

list = [b, c, a]

print "before sorting:"
print list
print

list.sort()

print "after sorting:"
print list
print

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

========= WAS CANCELLED BY =======:
Path: news.sol.net!spool1-milwwi.newsops.execpc.com!newsfeeds.sol.net!news-out.visi.com!hermes.visi.com!newsfeed.berkeley.edu!ucberkeley!feeder.kornet.net!news1.kornet.net!ua4canc3ll3r
From: "Mark McEahern" <markjunk at mceahern.com>
Newsgroups: comp.lang.python
Subject: cmsg cancel <hUHW7.7906$dG.3286832 at news1.rdc1.sdca.home.com>
Control: cancel <hUHW7.7906$dG.3286832 at news1.rdc1.sdca.home.com>
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 news1.rdc1.sdca.home.com>
NNTP-Posting-Host: 211.57.49.2
X-Trace: news2.kornet.net 1009775718 27193 211.57.49.2 (31 Dec 2001 05:15:18 GMT)
X-Complaints-To: usenet at news2.kornet.net
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