Inheriting str object

Benjamin Niemann pink at odahoda.de
Mon Feb 5 06:21:09 EST 2007


Marc 'BlackJack' Rintsch wrote:

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

yes, but the 'upper' method is the problem here.
So you'd have to override all string methods, like

class myStr(str):
    ...

    def upper(self):
        return myStr(str.upper(self))


And I'm not sure, if it then works in the intended way...
What you are probably looking for, is to extend the 'str' class itself, so
every str instance has your added functionality.
Don't know, if this is possible at all, but usually it's not a good idea to
mess with the bowels of Python unless you have some greater surgical
skills.


HTH

-- 
Benjamin Niemann
Email: pink at odahoda dot de
WWW: http://pink.odahoda.de/



More information about the Python-list mailing list