REPOST: Re: cmp
jeff at ccvcorp.com
Thu Dec 27 20:22:15 CET 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,
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):
... return cmp(self.value, other.value)
... return -1
>>> a = test(1)
>>> b = test(2)
>>> c = test(2)
>>> a < b
>>> b is c
>>> b == c
========= WAS CANCELLED BY =======:
From: Jeff Shannon <jeff at ccvcorp.com>
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
Message-ID: <cancel.3C2B74E6.597B894D at ccvcorp.com>
X-Trace: news2.kornet.net 1009775633 27193 188.8.131.52 (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-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