subclassing str
Thomas Lotze
thomas.lotze at gmx.net
Tue Sep 14 09:58:17 EDT 2004
On Tue, 14 Sep 2004 09:30:43 -0400, Russell Blau wrote:
> I think you need to use __new__() instead of __init__(), like so:
Thanks, that did the trick.
>>>> 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)
I found it's actually possible to say seq[:] instead of str(seq)[1:-1],
which is less dependent on the exact format of the fancy representation.
So seq[:] seems to be a "trick" for getting at a sequence as it is,
without honouring its (string) representation. Thinking further, I wonder
what to do on non-sequence types, and whether there isn't a way to get to
an object's core that doesn't look like a trick. Or is it not all that
tricky after all?
> For more info, see http://www.python.org/2.2.1/descrintro.html#__new__
Thanks for the pointer.
--
Viele Grüße,
Thomas
More information about the Python-list
mailing list