Skip to main content
 首页 » 编程设计

python之如何在 python 中创建对象堆队列

2025年05月04日19unruledboy

我想在我用 python 创建的类上使用堆队列 ( http://docs.python.org/2/library/heapq.html ):

class Dog: 
  def __init__(self, name, age): 
    self.name = name 
    self.age = age 

我想比较堆队列中狗的年龄。我如何告诉 python 按年龄比较我的对象?换句话说,我能以某种方式用 Python 编写一个“比较器”吗?

请您参考如下方法:

你必须在你的类中添加一个 __lt__ 方法:

def __lt__(self, other): 
    return self.age < other.age 

如果您想要安全起见,请添加一个 __eq__ 方法,并使用 functools.total_ordering 装饰您的类,以添加其他比较运算符。