10

I have a class representing something with a few fields. When a list of instances of this class is sorted, I want them to be sorted in a particular order (get a particular key from each one). I can just do list.sort(key=Classname.sortKey) and define a sortKey method, but I'd rather just do list.sort() and have it work out. I figure I can do this by overriding __cmp__. However, what do I do when I'm comparing with something that is not my data type? I figure something like...

def __cmp__(self, o):
    if isinstance(o, MyClass):
        return cmp(self.sortKey(), o.sortKey())
    return object.__cmp__(self, o) ##**wrong

but that works instead. I don't care what ordering they take in a heterogeneous list. I would just return 0 but then stuff like MyClass(...) == x is always true, for any x not an instance of MyClass.

1 Answer 1

13

Check out http://wiki.python.org/moin/HowTo/Sorting/

You want to override __lt__ in your class for the built in sort function to work the way you described.

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.