Overriding UserList methods

Daniel Klein danielk at aracnet.com
Tue Mar 6 10:04:28 EST 2001


On Mon, 5 Mar 2001 00:52:40 -0500, "Steve Holden" <sholden at holdenweb.com>
wrote:

>"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?

One of the reasons for subclassing UserList is to provide additional instance
variables. So I need my own __init__ method to initialize this, don't I?

>>     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!

Again, I need to provide append() with some specialized code, ie I need to
ensure that only certain types of objects are in the list.

>> 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.

Good suggestion! I don't need this for here but I might use it elsewhere.

> Hope this helps.

Yes, it did. Thanks.

Daniel Klein




More information about the Python-list mailing list