subclassing Python types

Arnaud Delobelle arnodel at googlemail.com
Thu Aug 30 15:42:44 EDT 2007


On Aug 30, 8:24 pm, zzbba... at aol.com wrote:
> On Aug 30, 12:18 pm, Wildemar Wildenburger
>
>
>
> <lasses_w... at klapptsowieso.net> wrote:
> > zzbba... at aol.com wrote:
> > > I have read that you can derive from the base classes such as str,
> > > list, dict.
>
> > > I guess this would look like:
>
> > > def MyString(str):
> > > def MyList(list):
> > > def MyDict(dict):
>
> > Well, replace 'def' with 'class' and you're right.
>
> > > How do you access the data that is contained in the super class?
>
> > This way:
> >  >>> class MyList(list):
> > ...    def do_something(self):
> > ...       self.append(3)
> > ...       print self
> > ...
> >  >>> l = MyList((1, 2))
> >  >>> l
> > [1, 2]
> >  >>> l.do_something()
> > [1, 2, 3]
>
> > That is: Whenever you want to refer to the value refer to self (that is,
> > refer to the instance of your class).
>
> > /W
>
> Ok, thanks.
>
> So it's:
> class MyString(str):
>    def __init__(self,strInput):
>       self = strInput

No. Well in this case it seems to work as the method str.__new__ is
called first which does what you intend to do in your example. But try
this:

>>> class Upper(str):
...     def __init__(self, s):
...             self = s.upper()
...
>>> Upper('camelot')
'camelot'

Doesn't work (should be 'CAMELOT', shouldn't it?)!
To understand why it doesn't behave as you expect, and how to achieve
what you want,  see "Overriding the __new__ method" in GvR's article
"Unifying types and classes in Python 2.2" (http://www.python.org/
download/releases/2.2.3/descrintro/#__new__).

HTH

--
Arnaud





More information about the Python-list mailing list