Subclassing builtin types

Steve Holden sholden at holdenweb.com
Sun Mar 4 12:41:55 EST 2001


"Daniel Klein" <danielk at aracnet.com> wrote in message
news:i6u4atslg4euv732pvaujk6u036kemcidf at 4ax.com...
> One of the classes I have to write  is merely a wrapper around a 'list'
object.
> A very abreviated example,
>
> class MyParams:
>       def __init__(self):
>             self.parameters = []
>       def append(self, object):
>             self.parameters.append(object)
>       def insert(self, i, object):
>             self.parameters.insert(i, object)
>       def del(self, i):
>             del self.parameters[i]
> etc, etc...
>
> This would allow me to do things like
>
> p = MyParams()
> p.append('foo')
>
> Since I know you are going to ask :-), there are two main reasons I need
to do
> this:
>
> 1) I need to ensure that a certain 'capacity' is not exceeded. I will
probably
> have class variable which is checked in all methods which add objects to
> 'parameters' and then raise an exception if 'capacity' is exceeded.
>
> 2) I can only allow certain types of objects to be added to the list, so
these
> too will be checked where necessary and appropriate exceptions raised.
>
> What I would _REALLY_ like to do is subclass list something like
>
> class MyParams(List):
>
> so that I can inherit all of the list methods and only override the ones I
need
> to. In Smalltalk this would be accomplished simply with
>
> OrderedCollection subclass: #MyParams
>
> I had actually thought of creating a generic List class that could be
reused in
> cases like this.
>
> So two questions:
>
> 1) Are wrapper classes for the builtin types a feasible (and pythonic)
thing to
> do?
>
Yes and yes: so feasible the library includes a UserList class which
provides esxactly what you seem to want: it wraps a list inside a class so
you can inherit from it!

> 2) Are there another ways to accomplish what I'm trying to do here without
> creating my own class hierarchy?
>
> Thanks for any and all help, you people have been a wonderful lot to deal
with
> during this new-language learning period.
>
> Daniel Klein
> Portland OR USA
>
Delegation is also a useful trick. I've just published an ftpStream class
which delegates most of its actions to an ftplib.FTP object by providing its
own __getattr__() method. Follow the public-domain Python link from
http://www.holdenweb.com/

regards
 Steve






More information about the Python-list mailing list