General q. `bout subclassing
Thomas Wouters
thomas at xs4all.nl
Tue Nov 2 09:16:57 EST 1999
On Tue, Nov 02, 1999 at 02:30:41PM +0100, Thomas Weholt wrote:
> Simple one :
> How do I subclass fundamental stuff like lists etc,
You dont.
> tried something like :
>
> > >>> class my_list([]):
> > ... a = ''
> > ...
> > Traceback (innermost last):
> > File "", line 1, in ?
> > TypeError: base is not a class object
> > >>>
> >
> Huh ??
built-in types, and types provided by C extention modules (as opposed to
Python modules) are not 'full' objects in the sense that Python objects are
-- they do not have a __dict__ attribute listening all attributes, and they
do not have a __class__ attribute pointing to the 'parent' class. You also
can't subclass them. Instead, you have to wrap them in a base class, and
then extend them:
Class MyList:
def __init__(self, orig=None):
self.reallist = (orig or [])[:]
def __getitem__(self, index):
return self.reallist[index]
def __setitem__(self, index, value):
self.reallist[index] = value
<etc>
Class MySubclassedList(MyList):
<etc>
The standard Python library provides such wrappers, and do their best to
simulate built-in types. They do a pretty good job, too ;-) Check out
the 'UserList' and 'UserDict' modules -- they are, by necessity, written in
python. Very readable :-)
I believe the classless-builtin-types problem is supposed to be fixed by
Python 2.0. But I've seen that in response to so many ideas... Either
python2 is going to be as bloated as C++, or it is a generic 'when hell
freezes over on a midsummer christmas easter-wednesday'-type answer. :)
python-forever'ly y'rs,
--
Thomas Wouters <thomas at xs4all.net>
Hi! I'm a .signature virus! copy me into your .signature file to help me spread!
More information about the Python-list
mailing list