__cmp__方法在Python 2.x中没有按预期工作?

mon*_*nny 6 python cmp 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)
Run Code Online (Sandbox Code Playgroud)

这里的输出是:

cmp method called with self=hello,other=there
True
False
Run Code Online (Sandbox Code Playgroud)

这不是我的预期:我试图说'如果名称字段相等,则两个实例相等'.

如果我只是return False__cmp__功能,这也报告True!! 如果我回来-1,那么我得到False- 但是因为我想要比较字符串,这感觉不对.

我在这做错了什么?

ken*_*ytm 10

__cmp__(x,y)应该返回一个负数(例如-1),如果x < y,正数(例如1)if x > y和0 if x == y.你永远不应该用它返回一个布尔值.

你正在超载的是什么__eq__(x, y).


jsb*_*eno 5

__cmp__当self <other,self == other,self> other respectly时,该方法应该返回-1,0或1.

你可以做

return cmp(self.name, other.name)
Run Code Online (Sandbox Code Playgroud)

在您的代码中获得正确的结果