Subclassing list and splicing

K

Kreso

I am subclassing list class and it basically works, but I don't
understand why after splicing these mylist objects I don't get
returned mylist objects. What I get are list objects:


class mylist(list):

def __init__(self):
list.__init__(self)


k = mylist()
k.append(1)
k.append(2)
k.append(3)
print type(k) # prints <class '__main__.mylist'> as expected
m = k[:1]
print type(m) # prints <type 'list'> ???


I would prefer that resulting object m belonged to myclist class.
How to obtain such behaviour? Must I somehow implement __getslice__
method myself?

(It's python 2.5.2, BTW)
 
E

Emile van Sebille

On 9/3/2009 10:10 AM Kreso said...
I am subclassing list class and it basically works, but I don't
understand why after splicing these mylist objects I don't get
returned mylist objects. What I get are list objects:
I would prefer that resulting object m belonged to myclist class.
How to obtain such behaviour? Must I somehow implement __getslice__
method myself?

Yep -- something like:

class mylist(list):
def __init__(self,val=None):
if val is None:
list.__init__(self)
else:
list.__init__(self,val)
def __getslice__(self,slstart,slend,slstep=None):
return mylist(self[slstart:slend:slstep])


Emile
 
K

Kreso

Kreso said:
I would prefer that resulting object m belonged to myclist class.

I forgot to add that mylist instances in my case have some attributes (that's
why I need special container class in the first place) which should be
preserved after splicing.
In my simple understaning of python it looks to me that list splicing
has to involve copying (i.e. cannot be done only by referencing), and since
base class 'list' doesn't know anything about mylist attributes, I will certainly
have to override list's __getslice__ method, right? The only question
is how to re-use as much of the 'lists' methods as possible, so that
at list I don't need to write the code for copying of contained
elements.
 
N

Nobody

I would prefer that resulting object m belonged to myclist class.
How to obtain such behaviour? Must I somehow implement __getslice__
method myself?

Yes; you should also implement __getitem__(), as this is used for extended
slices.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

Forum statistics

Threads
473,995
Messages
2,570,225
Members
46,815
Latest member
treekmostly22

Latest Threads

Top