为什么我不能像 Python 2 一样在 Python 3 中使用 __cmp__ 方法? [英] Why can't I use the method __cmp__ in Python 3 as for Python 2?

查看:59
本文介绍了为什么我不能像 Python 2 一样在 Python 3 中使用 __cmp__ 方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面一段代码

类点:def __init__(self, x, y):自我.x = x自我.y = ydef dispc(self):return ('(' + str(self.x) + ',' + str(self.y) + ')')def __cmp__(自我,其他):返回 ((self.x > other.x) 和 (self.y > other.y))

在 Python 2 中工作正常,但在 Python 3 中出现错误:

<预><代码>>>>p=点(2,3)>>>q=点(3,4)>>>p>q回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中类型错误:无法排序的类型:point() >观点()

<小时>

它只适用于 ==!=.

解决方案

你需要在 Python 3 中提供丰富的排序比较方法,它们是 __lt__, __gt__, __le__, __ge__, __eq____ne__.另请参阅:PEP 207 -- 丰富的比较.

__cmp__ 不再使用.

<小时>

更具体地说,__lt__selfother为参数,需要返回self是否小于比其他.例如:

class Point(object):...def __lt__(自我,其他):返回 ((self.x < other.x) 和 (self.y < other.y))

(这不是一个明智的比较实现,但很难说你想要什么.)

所以如果你有以下情况:

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

这将等同于:

p1.__lt__(p2)

将返回 True.

如果点相等,

__eq__ 将返回 True,否则返回 False.其他方法类似.

<小时>

如果您使用 functools.total_ordering 装饰器,你只需要实现 eg__lt____eq__ 方法:

from functools import total_ordering@total_ordering类点(对象):def __lt__(自我,其他):...def __eq__(自我,其他):...

The following piece of code

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))

works fine in Python 2, but in Python 3 I get an error:

>>> 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()


It only works for == and !=.

解决方案

You need to provide the rich comparison methods for ordering in Python 3, which are __lt__, __gt__, __le__, __ge__, __eq__, and __ne__. See also: PEP 207 -- Rich Comparisons.

__cmp__ is no longer used.


More specifically, __lt__ takes self and other as arguments, and needs to return whether self is less than other. For example:

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

(This isn't a sensible comparison implementation, but it's hard to tell what you were going for.)

So if you have the following situation:

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

p1 < p2

This will be equivalent to:

p1.__lt__(p2)

which would return True.

__eq__ would return True if the points are equal and False otherwise. The other methods work analogously.


If you use the functools.total_ordering decorator, you only need to implement e.g. the __lt__ and __eq__ methods:

from functools import total_ordering

@total_ordering
class Point(object):
    def __lt__(self, other):
        ...

    def __eq__(self, other):
        ...

这篇关于为什么我不能像 Python 2 一样在 Python 3 中使用 __cmp__ 方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆