扩展str类以获取其他参数

Joh*_*cés 4 python string class extend

我想创建一个特殊类型的字符串的新类.我希望它继承str类的所有方法,但我希望能够传递一个它可以使用的附加参数.像这样的东西:

class URIString(str, ns = namespace): # ns defaults to global variable namespace
    def getLocalName(self):
        return self[(self.find(ns)+len(ns)):] # self should still act like a string
        # return everything in the string after the namespace
Run Code Online (Sandbox Code Playgroud)

我知道语法不对.但希望它传达出我想要实现的想法.

Gar*_*tty 7

你会想做这样的事情:

class URIString(str):
    _default_namespace = "default"

    def __init__(self, value, namespace=_default_namespace):
        self.namespace = namespace

    def __new__(cls, value, namespace=_default_namespace):
        return super().__new__(cls, value)      

    @property
    def local_name(self):
        return self[(self.find(self.namespace)+len(self.namespace)):]
Run Code Online (Sandbox Code Playgroud)

我已经使用@property装饰器getLocalName()变成了属性local_name- 在python中,getters/setter被认为是不好的做法.

注意前Python 3.x,你需要使用super(URIString, cls).__new__(cls, value).