Making your objects sortable in Python is very simple: add the __cmp__ function and the logic to compare the two objects and you are done!
-
class person:
-
def __init__(self, name, age):
-
self.name = name
-
self.age = age
-
-
def __str__(self):
-
return 'Person %s (%d)' % (self.name, self.age)
-
-
def __cmp__(self, other):
-
return cmp(self.name+str(self.age), other.name+str(other.age))
-
-
lista = [
-
person('Ren Smith', 24),
-
person('Aohn Doe', 31),
-
person('Aohn Doe', 22),
-
person('Eneko Alonso', 30),
-
person('Ren Gomas', 34)
-
]
-
-
for person in lista:
-
print person
-
print '—–'
-
for person in sorted(lista):
-
print person
As you can see, you can totally customize your __cmp__ method and compare any class members.
Download the code: http://enekoalonso.com/svn/python/classes/sorting-objects.py