[Tutor] Sorting Instance Attributes
Magnus Lycka
magnus@thinkware.se
Thu Dec 12 17:40:03 2002
At 21:40 2002-12-11 -0600, Don Arnold wrote:
>This got me to thinking (which can be dangerous at times): what if you don't
>always want to sort by the same attribute? I played around a little, and
>here's what I came up with:
>
>def setStudentKey(key):
> """builds the comparison function on the fly"""
> c = 'def studentCompare(l,r):\n\treturn cmp(str(l.%s),str(r.%s))\n' \
> % (key, key)
> exec(c,__builtins__.__dict__)
Another approach would be to do something like this:
>>> class Student:
... compare = 'lname'
... def __init__(self, fname, lname):
... self.fname = fname
... self.lname = lname
... def __str__(self):
... return "%s %s" % (self.fname, self.lname)
... def setStudentKey(self, attribute):
... if attribute not in self.__dict__.keys():
... return AttributeError
... Student.compare = attribute
... def __cmp__(self, other):
... return cmp(getattr(self, Student.compare),
... getattr(other, Student.compare))
...
>>> a = Student('Allan', 'Zak')
>>> b = Student('Barney', 'Yak')
>>> c = Student('Caesar', 'Xak')
>>> l = [a,b,c]
>>> l.sort()
>>> map(str, l)
['Caesar Xak', 'Barney Yak', 'Allan Zak']
>>> b.setStudentKey('fname')
>>> l.sort()
>>> map(str, l)
['Allan Zak', 'Barney Yak', 'Caesar Xak']
>>> a.setStudentKey('lname')
>>> l.sort()
>>> map(str, l)
['Caesar Xak', 'Barney Yak', 'Allan Zak']
>>>
--
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/ mailto:magnus@thinkware.se