Почему параметр cmp удален из сортировки / сортировки в Python3.0?
от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).
Я не понимаю, почему cmp удаляется в py3.0
рассмотрим этот пример:
>>> 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 __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__
сделать жизнь проще?