REPOST: Re: cmp
Jeff Shannon
jeff at ccvcorp.com
Thu Dec 27 14:22:15 EST 2001
Matt Russell wrote:
> Well, I just made myself look silly. I admit it...
>
> when I type 1==1 into the interpreter, I thought if it was true, the
> result is 1 - this is right. But cmp(1,1) actually returns 0 (in
> accordance to the docs)
>
> But why then are we given the mechanism to compare instances of
> classes via the __cmp__ def ?
>
> Collegues of mine have used this to return 1 (truth) if two instances
> are equal (instanceA==instanceB).... this obviously wasn't the
> intended purpose. (__cmp__ shuold return 0 if the result of cmp(a,b)
> is to be trusted??
>
> Perhaps then could someone explain to me how one compares classes
> useing the == operator, or indeed if this bad programming practice.
>
> I hope I didn't waste too much of guido's time when I posted a bug on
> sourceforge :(
cmp(a, b) is not a boolean function, as your colleagues apparently feel
it should be. It's actually a trinary function--it can return -1, 0, or
+1, representing a being less than, equal to, or greater than b,
respectively.
Comparing classes with the == operator is fine. If you've declared a
__cmp__() for your class, then == will use that. If you haven't, then ==
uses 'is' -- in other words, it tests for object identity.
Note that if cmp(a, b) returns 0, then a == b will evaluate to 1.
>>> class test:
... def __init__(self, val):
... self.value = val
... def __cmp__(self, other):
... try:
... return cmp(self.value, other.value)
... except:
... return -1
...
>>> a = test(1)
>>> b = test(2)
>>> c = test(2)
>>> a < b
1
>>> b is c
0
>>> b == c
1
>>>
Jeff Shannon
Technician/Programmer
Credit International
========= WAS CANCELLED BY =======:
Path: news.sol.net!spool1-milwwi.newsops.execpc.com!newsfeeds.sol.net!news-out.visi.com!hermes.visi.com!newsfeed.direct.ca!look.ca!newsfeed.dacom.co.kr!feeder.kornet.net!news1.kornet.net!ua4canc3ll3r
From: Jeff Shannon <jeff at ccvcorp.com>
Newsgroups: comp.lang.python
Subject: cmsg cancel <3C2B74E6.597B894D at ccvcorp.com>
Control: cancel <3C2B74E6.597B894D at ccvcorp.com>
Date: Mon, 31 Dec 2001 04:07:35 GMT
Organization: A poorly-installed InterNetNews site
Lines: 2
Message-ID: <cancel.3C2B74E6.597B894D at ccvcorp.com>
NNTP-Posting-Host: 211.57.49.2
X-Trace: news2.kornet.net 1009775633 27193 211.57.49.2 (31 Dec 2001 05:13:53 GMT)
X-Complaints-To: usenet at news2.kornet.net
NNTP-Posting-Date: Mon, 31 Dec 2001 05:13:53 +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