如何在Python中使用__cmp__方法比较类中的两个对象?

时间:2016-10-04 15:45:30

标签: python python-2.7

class Box(object):
def __init__(self, ival):
    self.value = ival
def __cmp__(self,other):
    if self.value < other:
        return 
    elif self.value > other:
        return 1
    else:return 0

但是,当我想用​​以下方法测试该程序时:

Box(2) < Box(2)
Box(2) <= Box(2)
Box(1) >= Box(2)
Box(3) > Box(2)
Box(0) == Box(1)
Box(0) != Box(0)

以下代码的一部分:

Box(1) >= Box(2)
Box(3) > Box(2)
Box(0) == Box(1)

已经显示

  

TypeError:需要一个整数

任何人都知道为什么?

编辑:我之前添加了-1但不知何故我删除了它.- 抱歉问这样粗心的问题!

4 个答案:

答案 0 :(得分:3)

Python的__cmp__魔术方法返回一个整数&gt; 0如果更大,0如果相等,则&lt; 0如果更少。您可以在docs

中看到

对于'小于'的比较,你的__cmp__函数返回None。

class Box(object):
    def __init__(self, ival):
        self.value = ival
    def __cmp__(self,other):
        if self.value < other:
            return   # return None   <--------- bad
        elif self.value > other:
            return 1
        else:return 0

应该是:

class Box(object):
    def __init__(self, ival):
        self.value = ival
    def __cmp__(self,other):
        if self.value < other:
            return -1  # <--------- yay!
        elif self.value > other:
            return 1
        else:
            return 0

正如其他人指出的那样,如果您要将Box与另一个Box进行比较,则应修改__cmp__方法以比较other.value,而不仅仅是other

class Box(object):
    def __init__(self, ival):
        self.value = ival
    def __cmp__(self,other):
        if self.value < other.value:
            return -1
        elif self.value > other.value:
            return 1
        else:
            return 0

答案 1 :(得分:1)

您必须将self.valueother.value进行比较:

def __cmp__(self,other):
    if self.value < other.value:
        return -1
    elif self.value > other.value:
        return 1
    else:return 0

否则你要将整数与对象进行比较

答案 2 :(得分:0)

__cmp__上的

Doc reference

  

返回 负整数如果self < other如果self == other,则正整数如果self > other

所以你的所有分支都应该返回一个整数,但if分支正在返回None

答案 3 :(得分:0)

请注意,现在不推荐使用__cmp__方法ID - 您应该使用所谓的&#34;丰富的比较&#34;方法 - __eq__和朋友。

由于您尝试将整数与Box对象进行比较而导致错误,并且未定义此类比较。也许你需要的更像是

        if self.value < other.value:
            return -1
        elif self.value > other.value:
            return 1
        else:
            return 0

但您可能需要考虑other是否为Box。如果不是,比较意味着什么呢?