Inheriting str object

BJörn Lindqvist bjourne at gmail.com
Mon Feb 5 08:39:27 EST 2007


On 5 Feb 2007 02:48:08 -0800, kungfoobar at gmail.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!

You could use the proxy pattern:

class GreeterString(object):
    def __init__(self, str):
        self.proxy = str

    def hello(self):
        return 'hello ' + self.proxy

    def __getattr__(self, attr):
        if attr in dir(self.proxy):
            proxy_attr = getattr(self.proxy, attr)
            if callable(proxy_attr):
                def wrapper(*args, **kwargs):
                    return self.__class__(proxy_attr())
                return wrapper

    def __str__(self):
        return self.proxy.__str__()


gs = GreeterString('world')
print gs.upper().hello()

Magic methods has to be overridden manually, I think.

-- 
mvh Björn



More information about the Python-list mailing list