优先级队列无法识别 __cmp__ 中的函数 Python

Priority Queue Doesn't Recognize __cmp__ Function In Python

我正在尝试在 Python 中实现优先级队列。我正在关注我在网上找到的 exampleSkill class 覆盖 __cmp__ 方法,以便优先级队列可以自行排序。当我 运行:

时出现错误
TypeError: unorderable types: Skill() < Skill()

我在网上找到了几个例子,它们说只要重载 __cmp__() 方法,优先级队列就应该是好的。

try:
    import Queue as Q  # ver. < 3.0
except ImportError:
    import queue as Q

class Skill(object):
    def __init__(self, priority, description):
        self.priority = priority
        self.description = description
        print ('New Level:', description)
        return
    def __cmp__(self, other):
        return cmp(self.priority, other.priority)

q = Q.PriorityQueue()

q.put(Skill(5, 'Proficient'))
q.put(Skill(10, 'Expert'))
q.put(Skill(1, 'Novice'))

while not q.empty():
    next_level = q.get()
    print ('Processing level:', next_level.description)

我目前 运行正在我的计算机上安装 Python 3.4.1。

cmp__cmp__ 仅在 Python 2.x 中使用;它们不再存在于 Python 3.x 中。现在,您可以通过实现 __eq____ne____lt____gt____ge____le__.[=25 来直接重载比较运算符=]

您可以在 Ordering Comparisons 下的 Python 3.0 页面的新增功能中阅读有关此更改的信息:

The cmp() function should be treated as gone, and the __cmp__() special method is no longer supported. Use __lt__() for sorting, __eq__() with __hash__(), and other rich comparisons as needed.

__cmp__ 已在 Python3 中删除,您应该使用丰富的比较 dunder 方法来代替 __lt____le____eq____ne__, __gt__, __ge__.

它们的工作方式如下:

a < b  # a.__lt__(b)
a <= b # a.__le__(b)
a == b # a.__eq__(b)
a != b # a.__ne__(b)
a > b  # a.__gt__(b)
a >= b # a.__ge__(b)

您还可以使用 class 装饰器 functools.total_ordering,它允许您指定 __eq____lt__, __le__, __gt__, __ge__ 中的任何一个,它会推断出其余的富人比较方法。

import functools

@functools.total_ordering
class NewNumber(object):
    def __init__(self, num):
        self.num = num
    def __lt__(self, other):
        return self.num < getattr(other, 'num', other)
        # fancy way of doing self.num < other.num if other.num exists,
        #   else to do self.num < other
    def __eq__(self, other):
        return self.num == getattr(other, 'num', other)