[Tutor] subclassing list -- slicing doesn't preserve type
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:
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):
>>> l = MyList()
>>> l2 = l[1:]
>>> isinstance(l2, MyList)
More information about the Tutor