[Tutor] custom container subclassing list-- slices are lists!?
Marcus Goldfish
magoldfish at gmail.com
Mon Aug 21 23:17:00 CEST 2006
On 8/21/06, Marcus Goldfish <magoldfish at gmail.com> wrote:
> I'd like to sublcass the built-in list type to create my own container.
> How can I make slices of the list be of type myclass-- currently they are
> lists. Example:
>
> >>> class MyFoo(list):
> def __init__(self, inlist):
> self = inlist[:]
> >>> me = MyFoo(range(10))
> >>> type(me)
> <class '__main__.MyFoo'>
>
> >>> type(me[0:3])
> <type 'list'>
>
First, a better example class:
class MyFoo(list):
def __init__(self, inlist):
list.__init__(self, inlist)
Second, I think I found a partial answer in the Feb 22, 2005 tutor thread
http://aspn.activestate.com/ASPN/Mail/Message/python-tutor/2502290. To
preserve type, I need to override some special functions. In the case of
slicing, I need to override with something like this:
def __getslice__(self, i, j):
return MyFoo(list.__getslice__(self, i, j))
This seems straightforward, but raises other questions: what other functions
should I override, e.g., __add__, __radd__? Is there a preferred pythonic
way to creating a custom list container?
Finally, should I slice-copy my input list, inlist, to prevent side effects,
or is this handled by list?
Thanks,
Marcus
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060821/80434ce3/attachment.html
More information about the Tutor
mailing list