Why no list heritable type?
steve at holdenweb.com
Thu Dec 16 22:07:59 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?
I think the thing you are really missing is the fact that list and the
other built-in types can be used as the basis for inheritance:
Python 2.4 (#1, Dec 4 2004, 20:10:33)
[GCC 3.3.3 (cygwin special)] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>> class fooList(list):
... def bar(self):
... for item in self:
... print "Bar:", item
>>> fl = fooList(('one', 'two', 'three'))
You do need to be somewhat careful, though, to understand the
initialisation mechanism of the new object-based types if you are going
to get the best out of them.
Steve Holden http://www.holdenweb.com/
Python Web Programming http://pydish.holdenweb.com/
Holden Web LLC +1 703 861 4237 +1 800 494 3119
More information about the Python-list