[Tutor] subclassing list -- slicing doesn't preserve type

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Wed Feb 23 01:29:47 CET 2005


> > > I'm trying to figure out how to subclass the list built-in.
>
> > You could do it e.g. like that:
> >
> > class Mylist (list):
> >     def __init__(self, seq=None):
> >         super(self.__class__, self).__init__(seq)
> >     def __getslice__(self, start, stop):
> >         return self.__class__(super(self.__class__, self).__getslice__(start, stop))
> >     def __getitem__(self, key):
> >         if isinstance(key, slice):
> >             return self.__class__(super(self.__class__, self).__getitem__(key))
> >         else:
> >             return super(self.__class__, self).__getitem__(key)


We might want to bring up that using inheritance here might be an
inappropriate OOP construct here.  It might be better to handle this sort
of thing by wrapping a list in a wrapper, and work through delegation.
In fact, that's essentially what UserList is.

I'm not sure I agree with the documentation of:

    http://www.python.org/doc/lib/module-UserList.html

where it says that subclassing 'list' is usually appropriate.  It seems
awfully messy to have to overload every method that can potentially
produce a new list.


And besides, all that work is being done in UserList already:

###
>>> from UserList import UserList
>>> class MyList(UserList):
...     pass
...
>>> l = MyList()
>>> l.append('a')
>>> l.append('b')
>>> l.append('c')
>>> l2 = l[1:]
>>> isinstance(l2, MyList)
True
###



More information about the Tutor mailing list