__Cmp__ method - doesn't it work 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 is here:

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

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

If I'm just return Falseout of function __cmp__, this also shows up as True!! If I come back -1, then I get False- but since I'm trying to compare strings, this doesn't seem right.

What am I doing wrong here?

+5
source share
5 answers

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

, , __eq__(x, y).

+9

__cmp__ -1, 0 1, self < , self == , > .

return cmp(self.name, other.name)

+5

__cmp__ __eq__.

__cmp__:

, self < , , self == other, , self > other.

__eq__ , , , __cmp__ , , , , __eq__, __ne__, __le__, __ge__, __lt__ __gt__.

__cmp__, __eq__, 5 .

cmp() __cmp__:

return cmp(self.name,other.name)

, Ignacio, Python 3.0, Python 2.x __cmp__ - .

+4

__cmp__() . __lt__(), __eq__() __gt__() .

, . .

+2

__cmp__, :

, self < , , self == other, a , self > other.

0

All Articles