1

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?

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.