[Tutor] subclassing list -- slicing doesn't preserve type
Lloyd Kvam
python at venix.com
Tue Feb 22 22:58:57 CET 2005
> Message: 2
> Date: Tue, 22 Feb 2005 13:53:44 +0100
> From: sigurd at 12move.de (Karl Pfl?sterer )
> Subject: Re: [Tutor] subclassing list -- slicing doesn't preserve type
> To: tutor at python.org
> Message-ID: <usm3olqbd.fsf at hamster.pflaesterer.de>
> Content-Type: text/plain; charset=us-ascii
>
> On 22 Feb 2005, bvande at po-box.mcgill.ca wrote:
>
> > 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)
I've written code like this and then gotten burned. It's atractive in
that you avoid hard-coding class names and it becomes simple
boiler-plate that could be pasted anywhere. The problem comes when you
create
class Mybetterlist(Mylist):
...
When a Mybetterclass instance provides the self,
super(self.__class__, self)
is Mylist. So you recurse into the same __getslice__ that you started
with instead of getting Mylist's super class.
I think (untested) that you really want
return self.__class__(super(Mylist, self).__<method name>__(<args>)
--
Lloyd Kvam
Venix Corp
More information about the Tutor
mailing list