[Tutor] class methods as argument
thomas coopman
thomas.coopman at gmail.com
Sat Feb 10 19:24:05 CET 2007
On Sat, 10 Feb 2007 09:04:15 -0500
Kent Johnson <kent37 at tds.net> wrote:
> thomas coopman wrote:
> >
> > also,
> > Is it better to use super in FooList? and how should I use it then?
>
> Actually I would say that FooList is not pulling its weight.
> SortedList already allows specialization by the compare function, so
> to create the equivalent of a FooList you just call
> SortedList(Foo.compare).
I know that in this example it's rather useless to create FooList, but
the subclasses I have of SortedList have other specializations so I
will keep using them.
>
> If you do want to keep FooList then you should call
> SortedList.__init__() to set the compare function.
> SortedList.__init__ is an unbound function so you call it like this:
> SortedList.__init__(self, Foo.compare)
This works.
I think I'll need to reed some more about super because I thought I had
to use super in this case.
>
> Another design you might want to consider - if you will always be
> sorting each type of list by the same compare method - is to define a
> __cmp__() method in each class that will be part of a SortedList and
> use plain comparison operators (< > etc) to do the compare.
That's the problem. I define for most of my classes a __cmp__() method
but, some classes have another way of being sorted, and that's why I
give the compare method as an argument in SortedList
>
> Finally note that Python's sort() function is very fast and flexible
> and it might be better just to sort the list when you need it to be
> sorted, rather than keeping it sorted. Or maybe what you really need
> is a heap (see the heapq module). If you really want to keep a sorted
> list, you should look at the bisect module, it might help.
I now use sort() when there is some data initially. After creation, I
insert data with my own bisect method, I also use it to search the data.
I mostly need the sorted list, because I want to detect when a object
is added with the same value of some item in the list and take
appropriate actions.
>
> Kent
>
Thomas
More information about the Tutor
mailing list