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

时间:2010-01-27 10:58:24

标签: python python-2.x cmp

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)

这里的输出是:

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

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

如果我只是return False函数中的__cmp__,则报告为True! 如果我返回-1,那么我会得到False - 但是因为我正在尝试比较字符串,所以感觉不对。

我在这里做错了什么?

5 个答案:

答案 0 :(得分:10)

如果__cmp__(x,y)

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

您正在重载的是__eq__(x, y)

答案 1 :(得分:5)

当{&lt; 1}}方法返回-1,0或1时另外,自我==其他,自我&gt;其他尊重。

你可以做到

__cmp__
在您的代码中

以获得正确的结果

答案 2 :(得分:4)

您将__cmp____eq__混淆。

From the documentation of __cmp__:

  

如果自我&lt;返回负整数其他,如果自我为零==其他,如果自我为正整数>其他

__eq__返回一个布尔值,确定两个对象是否相等,__cmp__返回一个整数,确定这两个对象是否大于或小于彼此,因此除非你有特定的{ {1}},__eq____ne____le____ge____lt__方法。

在您的情况下,您确实需要__gt__方法而不是__cmp__,因为它可以节省您为其他比较实施其他5种方法。

您可以使用cmp() function并在__eq__方法中添加以下内容:

__cmp__

注意,as highlighted by Ignacioisn't the preferred method in Python 3.0,但在Python 2.x中return cmp(self.name,other.name) 是可行的方法。

答案 3 :(得分:2)

__cmp__()已过时。相反,定义__lt__()__eq__()__gt__()

即便如此,你做错了。你应该返回一个整数。

答案 4 :(得分:0)

查找__cmp__的文档,你应该返回一个整数:

  

如果返回负整数   自我&lt;其他,零如果自我==其他,a   如果是自我的正整数>其他