Comparison function as class method: how?

Jeff Stewart object01 at hotmail.com
Thu May 8 12:34:52 EDT 2003


That helps a lot.  But what is the D-S-U idiom?

And how is someone supposed to know about staticmethod()?  I couldn't find
it anywhere in the Tutorial, Language Reference Index, or Library Reference
Index.  Is there a better place to go for documentation?

--
Jeff S.


"Alex Martelli" <aleax at aleax.it> wrote in message
news:kRuua.62389$3M4.1523097 at news1.tin.it...
> Using a clear terminology would help.  A class method is a special
> construct that receives a CLASS, rather than an INSTANCE, as its
> first argument (you can call it either on the class or on any of
> its instances).  I very much doubt you want that.  Much more likely
> you want a static method, which receives no automatic argument.  E.g.:
>
> class Tracker(object):
>     def __init__(self):
>         self.modtime = time.time()
>     def byModTime(a, b):
>         return cmp(a.modtime, b.modtime)
>     byModTime = staticmethod(byModTime)
>
> Now, given a list L of instances of Tracker, you can, if you wish,
> call L.sort(Tracker.byModTime).
>
> Note that this will of course be *WAY* slower than the D-S-U
> idiom, which you might also choose to encapsulate as a staticmethod:
>
>     def sortByTime(listofinstances):
>         auxlist = [(x.modtime, x) for x in listofinstances]
>         auxlist.sort()
>         listofinstances[:] = [x for mt, x in auxlist]
>     sortByTime = staticmethod(sortByTime)
>
> to be called as Tracker.sortByTime(L).  But, if you are in no hurry
> and have made a vow to never use D-S-U on Thursdays, the other
> approach should also work and produce the same ordering.
>
>
> Alex
>






More information about the Python-list mailing list