【发布时间】:2013-12-10 17:32:20
【问题描述】:
来自python wiki:
In Py3.0, the cmp parameter was removed entirely (as part of a larger effort to simplify and unify the language, eliminating the conflict between rich comparisons and the __cmp__ methods).
不明白py3.0中去掉cmp的原因
考虑这个例子:
>>> def numeric_compare(x, y):
return x - y
>>> sorted([5, 2, 4, 1, 3], cmp=numeric_compare)
[1, 2, 3, 4, 5]
现在考虑这个版本(推荐并兼容 3.0):
def cmp_to_key(mycmp):
'Convert a cmp= function into a key= function'
class K(object):
def __init__(self, obj, *args):
self.obj = obj
def __lt__(self, other):
return mycmp(self.obj, other.obj) < 0
def __gt__(self, other):
return mycmp(self.obj, other.obj) > 0
def __eq__(self, other):
return mycmp(self.obj, other.obj) == 0
def __le__(self, other):
return mycmp(self.obj, other.obj) <= 0
def __ge__(self, other):
return mycmp(self.obj, other.obj) >= 0
def __ne__(self, other):
return mycmp(self.obj, other.obj) != 0
return K
>>> sorted([5, 2, 4, 1, 3], key=cmp_to_key(reverse_numeric))
[5, 4, 3, 2, 1]
后者非常冗长,而前者仅用一行就达到了相同的目的。另一方面,我正在编写我想为其编写__cmp__ 方法的自定义类。从我在网上的一点阅读,建议写__lt__,__gt__,__eq__,__le__,__ge__,__ne__ and not __cmp__
再次,为什么这个建议?我不能只定义__cmp__让生活更简单吗?
【问题讨论】:
-
您问的是两个不同的事情,
__cmp__使类具有可比性的方法,以及用于自定义排序的排序函数的cmp关键字参数。当然,它们并非完全不相关,但无论如何它们都不是一回事。当您编写一个比较对象的cmp函数时,它并不关心它是使用__cmp__还是__lt__这样做;当您编写一个为您的对象创建键值的key函数时,它并不关心它是使用__cmp__还是__lt__(或两者都不使用)来这样做。那么,您要问的是这两个问题中的哪一个? -
(实际上,您可能会感到困惑的第三件事,
cmp函数,在 3.x 中也已删除。) -
各种cmp在3.X中都去掉了还是不推荐使用..正确的?
-
@user2708477:对,
__cmp__特殊方法永远不会被调用,任何与排序相关的函数都没有cmp参数,也没有内置的cmp函数。 -
@user2708477:没错。