I want to use a heap queue (http://docs.python.org/2/library/heapq.html) on a class I made in python:
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
I want to compare the dogs by age in the heap queue. How do I tell python to compare my objects by age? In other words, can I somehow write a "comparator" in python?
You will have to add a __lt__
method to your class:
def __lt__(self, other):
return self.age < other.age
If you want to be safe, add a __eq__
method as well and decorate your class with functools.total_ordering
to add the other comparison operators as well.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments