为什么我不能像Python 2一样在Python 3中使用__cmp__方法?

发布于 2021-01-29 19:34:44

下面的代码

class point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def dispc(self):
        return ('(' + str(self.x) + ',' + str(self.y) + ')')

    def __cmp__(self, other):
        return ((self.x > other.x) and (self.y > other.y))

在Python 2中可以正常工作,但是在Python 3中我得到一个错误:

>>> p=point(2,3)
>>> q=point(3,4)
>>> p>q
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unorderable types: point() > point()

它仅适用于==!=

关注者
0
被浏览
91
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    您需要提供在Python 3订货丰富的比较方法,这是
    __lt____gt____le____ge____eq__,和__ne__。另请参阅:PEP
    207-丰富的比较

    __cmp__不是 不再使用。


    更具体地说,__lt__selfother作为参数,并且需要返回是否self小于other。例如:

    class Point(object):
        ...
        def __lt__(self, other):
            return ((self.x < other.x) and (self.y < other.y))
    

    (这不是明智的比较实现,但是很难说出您要做什么。)

    因此,如果您有以下情况:

    p1 = Point(1, 2)
    p2 = Point(3, 4)
    
    p1 < p2
    

    这等效于:

    p1.__lt__(p2)
    

    这将返回True

    __eq__``True如果点相等False则返回,否则返回。其他方法类似地工作。


    如果使用functools.total_ordering装饰器,则只需实现例如__lt____eq__方法:

    from functools import total_ordering
    
    @total_ordering
    class Point(object):
        def __lt__(self, other):
            ...
    
        def __eq__(self, other):
            ...
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看