Overriding UserList methods

Steve Holden sholden at holdenweb.com
Mon Mar 5 00:52:40 EST 2001


"Daniel Klein" <danielk at aracnet.com> wrote in message
news:b566atck0ruu4tae8n1srrkntbmme26gor at 4ax.com...
> I must be missing something, cos I can't figure out how to override a
method
> using the UserList module. Here is some code:
>
> import UserList
> class MyList(UserList.UserList):
>       __def __init__(self):
>         UserList.UserList.__init__(self)
>
While this would work, I don't see it's strictly necessary. Why not just
inherit the __init__ method from UserList?

>     def append(self, object):
>         self.append(object)
>
> Understandably, this goes into a recursive frenzy until it hits the stack
> limit. :-(
>
Well, if you want *you* append method to make use of UserList's method you
would have to write

    def append(self, object):
        UserList.append(self, object)

Since all you are doing is reflecting the underlying UserList's append()
method, however, it would seem to make more sense to simply allow append()
to be inherited as well!

> The only way I could get this to work was to give the method another name,
ie
>
>     def add(self,object):   ## This works but I would rather use 'append'
>         self.append(object)   ## as the method name.
>
> So how can I override the append() method so that I can add my specialized
code
> to it?
>
> Daniel Klein

The clue is to use the unbound method from the superclass, as I showed you
above.

Another way would be to create a UserList object as an instance variable,
and then delegate methods to the UserList which you don't recognize, but
this might be going too far.  Hope this helps.

regards
 Steve






More information about the Python-list mailing list