Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

__cmp__ method is this not working as expected in Python 2.x?

class x:
    def __init__(self,name):
        self.name=name

    def __str__(self):
        return self.name

    def __cmp__(self,other):
        print("cmp method called with self="+str(self)+",other="+str(other))
        return self.name==other.name
       # return False


instance1=x("hello")
instance2=x("there")

print(instance1==instance2)
print(instance1.name==instance2.name)

The output here is:

cmp method called with self=hello,other=there
True
False

Which is not what I expected: I'm trying to say 'two instances are equal if the name fields are equal'.

If I simply return False from the __cmp__ function, this reports as True as well!! If I return -1, then I get False - but since I'm trying to compare strings, this doesn't feel right.

What am I doing wrong here?

like image 358
monojohnny Avatar asked Jan 27 '10 10:01

monojohnny


People also ask

What is __ cmp __ in Python?

In Python 2, __cmp__(self, other) implemented comparison between two objects, returning a negative value if self < other , positive if self > other , and zero if they were equal.

Does CMP work in Python 3?

cmp() does not work in python 3.

Why was cmp removed from Python 3?

from python wiki: In Py3. 0, the cmp parameter was removed entirely (as part of a larger effort to simplify and unify the language, eliminating the conflict between rich comparisons and the __cmp__ methods). The latter is very verbose and the same purpose is achieved in the former with just one line.

How do you use the CMP function in Python?

The cmp() is part of the python standard library which compares two integers. The result of comparison is -1 if the first integer is smaller than second and 1 if the first integer is greater than the second. If both are equal the result of cmp() is zero.


1 Answers

__cmp__(x,y) should return a negative number (e.g. -1) if x < y, a positive number (e.g. 1) if x > y and 0 if x == y. You should never return a boolean with it.

What you're overloading is __eq__(x, y).

like image 108
kennytm Avatar answered Sep 24 '22 16:09

kennytm