来自python 维基:
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__
Again,为什么要推荐这个?我不能只定义__cmp__
让生活更简单吗?