[Tutor] subclassing list -- slicing doesn't preserve type

Brian van den Broek bvande at po-box.mcgill.ca
Tue Feb 22 11:27:48 CET 2005


Hi all,

I'm trying to figure out how to subclass the list built-in.

.>>> class my_list(list):
          def __init__(self, sequence=None):
              list.__init__(self, sequence)
              self.spam = 1
		
.>>> mine = my_list((1,2,3,4))
.>>> mine.append(42)
.>>> mine
[1, 2, 3, 4, 42]
.>>> type(mine)
<class '__main__.my_list'>
.>>> damn = mine[1:3]
.>>> type(damn)
<type 'list'>
.>>> damn
[2, 3]
.>>>

I had thought that by subsclassing list I got all list-like properties
for free. Append (among others) are available for my_list instances.
But slicing returns a list, rather than a my_list. I can see that this
is list-like in it's way, but I'd rather have be so in mine ;-)	

I've read in the docs that UserList is discouraged, and in the
Nutshell that the __getslice__, etc. special methods are depreciated.

So, how can I get slicing to preserve the my_list type? And why does
the above class get so much for free, but not slicing?

Best, and thanks to all,

Brian vdB




More information about the Tutor mailing list