问题描述
在 python 中 - final 类是其他类不能继承的类,因为 various reasons(例如 - bool 类应该始终只有 2 个实例 - true 或 false)。
但是 - 就我而言,我想从 re.Match(正则表达式 Match 类)继承。问题是这个类是用 c 编写的,显然 Py_TPFLAGS_BASETYPE
标志在这个类的 c-python 实现中没有启用。
如果我想试试:
class Region(re.Match): # Error: type 're.Match' is not an acceptable base type
...
我不确定为什么在这种情况下没有启用此标志,但如果我至少可以尝试不受标志的限制,那就太好了。
有一种pythonic的方式来禁止继承(see)但是有一种python的方式来允许继承吗?
我可以尝试在 c 实现中通过 enabling this flag 解决它,但我想避免它。
我也可以尝试手动将每个需要的方法和属性重新引用到内部 match:re.Match 变量(也想避免这种情况)。
我正在寻找更“Pythonic”的解决方案。 有什么想法吗?
解决方法
我可能只是使用一个简单的代理对象 á la
class Region:
def __init__(self,match: re.Match):
self.__dict__["match"] = match # hoop jumped due to __setattr__
def __getattr__(self,key):
return getattr(self.match,key)
def __setattr__(self,key,value):
raise NotImplementedError("Regions are read-only")