[Tutor] class methods as argument
Kent Johnson
kent37 at tds.net
Sat Feb 10 15:04:15 CET 2007
thomas coopman wrote:
> Thank you for the explanation of bound and unbound methods.
> I understand that it is more common to use a bound method, but I don't
> think that I can use this because at the time I save the method, I don't
> know anything about the instances.
That would be an appropriate time to use unbound methods. From your
original example it wasn't clear.
>
> I use this for making a sorted list using any method you give as
> argument when you create the list. This class only gets to know it's
> instances when you add them.
>
> In [3]: class SortedList(object):
> ...: def __init__(self, compare):
> ...: self.compare = compare
> ...: def __add_(self, object):
> ...: for i in self.data:
> ...: self.compare(object, i)
> ...:
That looks OK so far.
>
> In [4]: class FooList(SortedList):
> ...: def __init__(self):
> ...: self.compare = Foo.compare
>
>
> __add__ doesn't do anything here of course, it is just an example,
> but I don't think that I can use a bound method in this case?
No. You can use an unbound method or an ordinary function with two
arguments.
>
> 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).
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)
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.
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.
Kent
More information about the Tutor
mailing list