扩展str类以接受额外参数
我想创建一个新的类,这个类是一种特殊的字符串。我希望它能继承所有字符串类(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
我知道这个语法不太对,但希望能传达出我想表达的意思。
1 个回答
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)):]
我使用了 @property
这个装饰器,把 getLocalName()
变成了一个叫 local_name
的属性。在Python中,使用获取器和设置器(getters/setters)被认为是不好的做法。
需要注意的是,在Python 3.x之前,你需要使用 super(URIString, cls).__new__(cls, value)
。