来自Python维基:
在Py3.0中,完全删除了cmp参数(作为简化和统一语言的更大努力的一部分,消除了富比较和__cmp__方法之间的冲突)。
我不明白为什么在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__
而不是__cmp__
。
那么,为什么要这样建议呢?我不能简单地定义一个__cmp__
方法吗?
__cmp__
方法使类可以比较,二是使用cmp
作为关键字参数来自定义排序函数。当然,它们并非完全没有关联,但它们绝不是同一件事情。当您编写一个比较对象的cmp
函数时,它不关心是否使用__cmp__
或__lt__
来进行比较;当您编写一个创建对象键值的key
函数时,它不关心是否使用__cmp__
或__lt__
(或都不用)来进行比较。那么,您是在问这两个问题中的哪一个? - abarnertcmp
函数,在3.x中也被移除了。 - abarnert__cmp__
特殊方法从来不会被调用,排序相关的函数中也没有cmp
参数,而且也没有内置的cmp
函数。 - abarnert