having fun with code

Making your objects sortable

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!

  1. class person:
  2.   def __init__(self, name, age):
  3.     self.name = name
  4.     self.age = age
  5.  
  6.   def __str__(self):
  7.     return 'Person %s (%d)' % (self.name, self.age)
  8.  
  9.   def __cmp__(self, other):
  10.     return cmp(self.name+str(self.age), other.name+str(other.age))
  11.  
  12. lista = [
  13.   person('Ren Smith', 24),
  14.   person('Aohn Doe', 31),
  15.   person('Aohn Doe', 22),
  16.   person('Eneko Alonso', 30),
  17.   person('Ren Gomas', 34)
  18. ]
  19.  
  20. for person in lista:
  21.   print person
  22. print '—–'
  23. for person in sorted(lista):
  24.   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

Related Posts:

Leave a Reply

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Additional comments powered by BackType

About the blog

This is a blog about development, focused mainly on Javascript but also other languages like python, shell scripts and more.

About the author

Eneko Alonso is a software engineer and UI developer with more than eight years of experience in software and web development. He lives in San Luis Obispo, California and works at LEVEL Studios.

Contact Info

Contact Info