Inheriting str object

Virgil Dupras hardcoded.software at gmail.com
Mon Feb 5 06:53:31 EST 2007


On Feb 5, 5:48 am, "kungfoo... at gmail.com" <kungfoo... 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?

To prevent operations with your myStr class to return a simple str
instance, you will have to override pretty much all str method, as
well as magic methods, such as __add__, __radd__ etc.. Major pain in
perspective. You might want to reconsider you developing strategy.




More information about the Python-list mailing list