[Tutor] Sorting Instance Attributes

Gonçalo Rodrigues op73418@mail.telepac.pt
Wed Dec 11 19:15:02 2002


----- Original Message -----
From: "Alan Colburn" <aicolburn@yahoo.com>
To: <tutor@python.org>
Sent: Wednesday, December 11, 2002 11:54 PM
Subject: [Tutor] Sorting Instance Attributes


> Hi all--
>
> I wrote a program awhile ago to help me keep track of
> attendance in my courses. Now, as an exercise, I've
> decided to rewrite the program OOP-style. Among other
> things, each student will be an object. The Student
> class constructor begins with this code:
>
> class Student:
>      def __init__(self, firstName, lastName):
>           self.firstName=firstName
>           self.lastName=lastName
>
> Adding a student into the course amounts to creating a
> new instance of the Student class. Now, onto my
> questions:
>
> 1. If I'd like to record most student information
> within individual Student class instances, what would
> be the recommended type (is that the right word?) to
> use for storing the collection of Student objects?
> List? Dictionary? I'll save the information via
> cpickle or shelve.

There is really no answer to this, depends on what you want to do with the
"collection of Student objects." Think about how you want to manage this
collection, what you want to do it. Is a list enough? Or probably it is
better to roll out your own "collection" class?

>
> 2. [Here's the one that I'm stumped on...] How do I
> sort objects via a single object attribute. In the
> example above, suppose I'd like to create a class
> list, sorted alphabetically via lastName?

Here Python's magic methods are useful. Consider the following

class Student(object):

    #Methods snipped.

    def __lt__(self, other):
        return self.lastname < other.lastname

I have added here one magic method - magic methods are signalled by being
surrounded by double underscores - that tells Python that this class
understands what is "less than". The method code is really simple: Since you
want alphabetical order we can just delegate to the order of builtin string
objects (There are probably some caveats with uppercase letters but let us
forget that for a moment). For more details on magic methods consult the
manuals.

Now, if you have a list, l say, of student objects, you can just call

l.sort()

and it will automatically sort the list by calling the __lt__ method.

Pretty cool stuff, I say.

>
> As always, thanks for your help! -- Al Colburn
>

With my best regards,
G. Rodrigues