subclassing str

Thomas Lotze thomas.lotze at gmx.net
Tue Sep 14 10:06:29 EDT 2004


On Tue, 14 Sep 2004 13:49:08 +0000, Duncan Booth wrote:

>>>> class SpecialString(str):
> 	def __new__(cls, s):
> 		if isinstance(s, SpecialString):
> 			s = s._raw()
> 		return str.__new__(cls, s)
[...]
> 	def _raw(self):
> 		return str.__str__(self)

Thanks a lot.

> 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).

Ah, good to have that piece of information.

> 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.

Yes, of course.

-- 
Viele Grüße,
Thomas




More information about the Python-list mailing list