Why no list heritable type?

Jeff Shannon jeff at ccvcorp.com
Thu Dec 16 22:05:57 CET 2004


James Stroud wrote:

>The thread "why not arrays" got me thinking. I would really like to inherit 
>from a list so that I can add methods based on its contents, say if I filled 
>it with a type of object and wanted to iterate over all objects. I have built 
>a wrapper around a list like this for general use:
>
>class list_of_objects:
>  def __init__(self):
>    self.data = []
>  def __len__(self):
>    return len(self.data)
>  etc ...
>
>Then it can be heritable and I can add or override methods. Why aren't built 
>in lists and dictionaries real heritable types that can save this kind of 
>patchwork? Is there a pythonic reason I am missing here?
>
>James
>
>
>  
>

But they *are* subclassable, since 2.2 at least:

PythonWin 2.2.1 (#34, Apr 15 2002, 09:51:39) [MSC 32 bit (Intel)] on win32.
Portions Copyright 1994-2001 Mark Hammond (mhammond at skippinet.com.au) - 
see 'Help/About PythonWin' for further copyright information.
 >>> type(list)
<type 'type'>
 >>> class my_list(list):
...     pass
...
 >>> type(my_list)
<type 'type'>
 >>> l = my_list()
 >>> l.append('foo')
 >>> l.extend(['bar', 'baz'])
 >>> l[2]
'baz'
 >>> l
['foo', 'bar', 'baz']
 >>> type(l)
<class '__main__.my_list'>
 >>>

Jeff Shannon
Technician/Programmer
Credit International




More information about the Python-list mailing list