> Message: 2
> Date: Tue, 22 Feb 2005 13:53:44 +0100
> From: [EMAIL PROTECTED] (Karl Pfl?sterer )
> Subject: Re: [Tutor] subclassing list -- slicing doesn't preserve type
> To: [email protected]
> Message-ID: <[EMAIL PROTECTED]>
> Content-Type: text/plain; charset=us-ascii
>
> On 22 Feb 2005, [EMAIL PROTECTED] 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
_______________________________________________
Tutor maillist - [email protected]
http://mail.python.org/mailman/listinfo/tutor