Problem in a str subclass

Michael Hudson mwh at python.net
Tue Nov 27 06:25:42 EST 2001


Manus Hand <manus at bullfrog-tech.com> writes:

> Can anyone explain why I get the following result?
> 
> Python 2.2b2 (#1, Nov 26 2001, 20:03:34)
> [GCC egcs-2.91.66 19990314/Linux (egcs-1.1.2 release)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> >>> class X(str):
> ...     def __init__(self, xx = None):
> ...             if not xx: xx = 'ye olde default value'
> ...             str.__init__(self, xx)
> ...
> >>> x = X('yo yo yo')
> >>> x
> 'yo yo yo'
> >>> x = X()
> >>> x
> ''
> >>>
> 
> I can't see why X() is not set to 'ye olde default value'

You need to do your initialisation inside the *class method* __new__;
by the time __init__ is called, the string has been constructed, and
as it's immutable...

You want to do this instead:

>>> class X(str):
...  def __new__(cls, xx="default"):
...   return str.__new__(cls, xx)
...
>>> X()
'default'


This is getting to be a FAQ, and it's a confusing point...

Cheers,
M.

-- 
7. It is easier to write an incorrect program than understand a
   correct one.
  -- Alan Perlis, http://www.cs.yale.edu/homes/perlis-alan/quotes.html



More information about the Python-list mailing list