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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With