How to subclass str in Python

后端 未结 5 2044
离开以前
离开以前 2020-12-24 07:09

I am trying to subclass str object, and add couple of methods to it. My main purpose is to learn how to do it. Where I am stuck is, am I supposed to subclass string in a met

5条回答
  •  臣服心动
    2020-12-24 07:29

    Here's a quick hack to do what you want: you basically intercept every function call, and, if you see that it's returning a string, you convert it back to your own class type.

    While this works in this simple example, it has some limitations. Among other things, operators such as the subscript operator are apparently not handled.

    class FunWrapper(object):
        def __init__(self, attr):
            self.attr = attr
    
        def __call__(self, *params, **args):
            ret = self.attr(*params, **args)
            if type(ret) is str:
                return Foo(ret)
            return ret
    
    class Foo(object):
        def __init__(self, string):
            self.string = string
    
        def __getattr__(self, attr):
            return FunWrapper(getattr(self.string, attr))
    
        def newMethod(self):
            return "*%s*" % self.string.upper()
    
    
    f = Foo('hello')
    print f.upper().newMethod().lower()
    

提交回复
热议问题