subclassing str
Duncan Booth
duncan.booth at invalid.invalid
Tue Sep 14 09:49:08 EDT 2004
Thomas Lotze wrote:
> Using instances
>
> x = SpecialString('foo')
> y = SpecialString(x)
>
> I want to get this behaviour:
>
> str(x) => '(foo)'
> str(y) => '(foo)'
>
> That is, I want to be able to make a SpecialString from anything that
> has a string representation, but at the same time leave a
> SpecialString untouched in the process. After all, it already is and
> gets formatted as a SpecialString.
>
Try this:
>>> class SpecialString(str):
def __new__(cls, s):
if isinstance(s, SpecialString):
s = s._raw()
return str.__new__(cls, s)
def __str__(self):
return "(" + self._raw() +")"
def _raw(self):
return str.__str__(self)
>>> x = SpecialString('foo')
>>> y = SpecialString(x)
>>> print x
(foo)
>>> print y
(foo)
You have to override __new__ as the default constructor for str calls the
__str__ method on its argument (which is where your extra parens appear).
Having added a method to bypass the formatting it makes sense to use it
inside __str__ as well otherwise the code is very sensitive to minor edits
e.g. changing it to:
return "(%s)" % self
would cause an infinite loop.
More information about the Python-list
mailing list