Inheriting str object

Marc 'BlackJack' Rintsch bj_666 at gmx.net
Mon Feb 5 06:12:18 EST 2007


In <1170672488.530515.181340 at k78g2000cwa.googlegroups.com>,
kungfoobar at gmail.com wrote:

> I want to have a str with custom methods, but I have this problem:
> 
> class myStr(str):
>     def hello(self):
>         return 'hello '+self
> 
> s=myStr('world')
> print s.hello() # prints 'hello world'
> s=s.upper()
> print s.hello() # expected to print 'hello WORLD', but s is no longer
> myStr, it's a regular str!
> 
> What can I do?

Return a `myStr` instance instead of a regular `str`:

    def hello(self):
        return myStr('hello ' + self)

Ciao,
	Marc 'BlackJack' Rintsch



More information about the Python-list mailing list