mat*_*ots 34 python sorting algorithm cmp python-internals
我在这里遇到了这个功能.
我对这将如何实现感到困惑 - 如何key通过cmp_to_key知道给定元素的"位置"而不检查给定元素与其他感兴趣元素的比较来生成函数?
Mar*_*ers 46
该cmp_to_key方法返回一个充当代理键的特殊对象:
class K(object):
    __slots__ = ['obj']
    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
    def __hash__(self):
        raise TypeError('hash not implemented')
排序时,每个键将与序列中的大多数其他键进行比较.位于0的元素是否低于或大于其他对象?
每当发生这种情况时,都会调用特殊方法钩子,因此__lt__或被__gt__调用,代理键会转而调用该cmp方法.
所以列表[1, 2, 3]被排序为[K(1), K(2), K(3)],如果K(1)比较,K(2)看看是否K(1)更低,然后K(1).__lt__(K(2))被调用,这被转换为mycmp(1, 2) < 0.
这是怎样的老cmp方法,工作无论如何 ; 返回-1,0或1,具体取决于第一个参数是否小于,等于或大于第二个参数.代理键将这些数字转换回比较运算符的布尔值.
代理键在任何时候都不需要知道关于绝对位置的任何信息.它只需要知道一个它正在与其他比较对象和特殊方法挂钩提供了其他对象.