为什么我不能像Python 2一样在Python 3中使用__cmp__方法?
下面的代码
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()
它仅适用于==
和!=
。
-
您需要提供在Python 3订货丰富的比较方法,这是
__lt__
,__gt__
,__le__
,__ge__
,__eq__
,和__ne__
。另请参阅:PEP
207-丰富的比较。__cmp__
是 不是 不再使用。
更具体地说,
__lt__
以self
和other
作为参数,并且需要返回是否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): ...