subclassing str

Russell Blau russblau at hotmail.com
Tue Sep 14 15:30:43 CEST 2004


"Thomas Lotze" <thomas.lotze at gmx.net> wrote in message
news:pan.2004.09.14.12.56.19.344018 at ID-174572.user.uni-berlin.de...
> For an application, I need a special string-like object. It has some
> specific semantics and behaves almost like a string, the only difference
> being that it's string representation should be somewhat fancy. I want
> to implement it as a subclass of str:
...
> 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.
>
> I tried the following:
>
> class SpecialString(str):
> def __str__(self):
> return "(" + self + ")"
>
> This makes for str(x) => '(foo)' but str(y) => '((foo))' - as expected.
>
> Does this accumulation of braces happen in the string itself, or does the
> formatting routine get called several times at each str() call? How to fix
> it, depending on the answer?
>
> I tried reimplementing __init__() in order to treat the case that a
> SpecialString is given to the constructor, but with little success.

I think you need to use __new__() instead of __init__(), like so:

>>> class SpecialString(str):
    def __new__(cls, seq):
        if isinstance(seq, SpecialString):
            return str.__new__(cls, str(seq)[1:-1])
        else:
            return str.__new__(cls, seq)
    def __str__(self):
        return "(" + self + ")"

>>> x = SpecialString("foo")
>>> y = SpecialString(x)
>>> print x
(foo)
>>> print y
(foo)

For more info, see http://www.python.org/2.2.1/descrintro.html#__new__


-- 
I don't actually read my hotmail account, but you can replace hotmail with
excite if you really want to reach me.





More information about the Python-list mailing list