list inheritance or delegation?

Simon Burton simonb at NOTTHISBIT.webone.com.au
Tue Mar 16 16:15:23 EST 2004


On Tue, 16 Mar 2004 12:51:15 -0800, george young wrote:

> [python 2.3.3, x86 linux]
> I need an object that behaves much like a list, but has some additional
> features.  It seems that I can do this either by inheriting from type
> list, or by emulating list by defining __len__, __getitem__, and maybe a
> bunch of  other methods.  Thirdly, I could inherit from UserList, but
> that's deprecated now.
> 
> Inheriting from list would save me implementing a bunch of methods that I
> might want.  But if I inherit from list, how do I get access to the data? 
> E.g., I need a customized 'setitem' method that does the insert and then
> does some other things too.  With UserList, I could:
> 
> class mylist(UserList):
>    def __setitem__(self,i,y):
> 	self.dostuff(y)
> 	self.data[i]=y
> 
> but when inheriting from 'list', I'm not sure how to do this.
> 

 class mylist(list):
    def __setitem__(self,i,y):
 	self.dostuff(y)
 	list.__setitem__(self,i,y)

same with __init__ etc.

> I couldn't find anything in the docs about inheriting from builtin types,
> though it seems to be an encouraged practice.  It seems like if one is
> encouraged to inherit from builtins, there needs to be at least a concise
> description of the 'inheritable api' for each such type. E.g. does
> __init__ or __new__ handle initial values.  Maybe I'm just missing
> something obvious...
> 	
> So, I'm asking:
> 1) what are the issues/tradoffs between inheriting from list and emulating
>    it with my own methods referencing a list data member.

One drawback is you (may) have to override
all list methods, rather than leave them undefined. The slicing stuff is particularly hairy.

Simon.

> 
> 2) how do I get enough access to list's data to do the inheritance.
> 
> 3) I'm whining about lack of documentation for #2.
> 
> Thanks,
>    George Young




More information about the Python-list mailing list