You can sort an array of myclass
by using the key
argument to the sorted
function:
sortedlist = sorted(myclasses, key=lambda obj: obj.myproperty)
Is there a way to define a natural ordering for our class? Perhaps some magic method so that we don't have to pass in a key each time?
e.g.,
class myclass:
def __init__(self,a,b):
self.key1 = a
self.key2 = b
def __sortkey__(self):
return self.key2
Or will it naturally work if we define __le__
perhaps?