On 8/21/06, Marcus Goldfish <[EMAIL PROTECTED]> 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
_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to