I thought researching this would be a good way to learn about builtin types, attributes, etc. I found http://stackoverflow.com/questions/7255655/ the most help. It seems that whilst it's not the full answer sought, its possible to go one further than a subclass of str, myStr('hello, how are you').trans(), which would return str, not myStr, on str methods. Some of the examples I found weren't printable or weren't consistent in returning the new type, hopefully the example below is. It's a subclass just of 'object' but it passes on method calls to str and ensures that any str result is converted to strT
class strT(object):
def __init__(self, value):
self.value = value
def __getattr__(self, attr):
attrib = getattr(self.value, attr)
if not callable(attrib):
return attrib
def wrapper(*params, **args):
result = attrib(*params, **args)
if type(result) is str:
return strT(result)
return result
return wrapper
def trans(self):
return strT(self.value + ' is hola')
def __str__(self):
return self.value
print strT(' HELLO ').strip().trans().lower()