Python: how to sort on a class method

Thanks to Mike Renfro, I learned how to sort a list of class objects according to a class method.

Ingredients:

  • Book class, with a Title attribute

  • Book.GetTitleProper() method (returns "Book Title, The" for "The Book Title"; an optional parameter returns the string lowercase, for case-neutral sorting)

  • Books class - subclassed from Python's list

  • Books.Sort_By_TitleProper() method

    def Sort_By_TitleProper(self, a, b):
      return cmp(a.GetTitleProper(1), b.GetTitleProper(1))
    

Cooking:

  1. Instantiate & load a Books instance

  2. objBooks.sort(objBooks.Sort_By_TitleProper)

    objBooks is sorted in-place.

Serving:

for eachBook in objBooks:
   print eachBook.GetListItemText(),
eachBook.GetTitleProper()

Written by Andrew Ittner in misc on Sat 09 August 2003. Tags: programming, python