【问题标题】:python inherent from 'final' classpython从'final'类继承
【发布时间】:2021-03-17 13:37:45
【问题描述】:

在 python 中 - final 类是其他类不能继承的类,因为 various reasons(例如 - bool 类应该始终只有 2 个实例 - true 或 false)。

但是 - 就我而言,我想从 re.Match (正则表达式 Match 类)继承。问题是这个类是用 c 编写的,显然在这个类的 c-python 实现中没有启用 Py_TPFLAGS_BASETYPE 标志。

如果我愿意尝试:

class Region(re.Match):  # Error: type 're.Match' is not an acceptable base type
   ...

我不确定为什么在这种情况下未启用此标志,但如果我至少可以尝试不受标志的限制,那就太好了。

有一种pythonic的方式来禁止继承(see)但是有没有一种python的方式来允许继承?

我可以尝试在c实现中通过enabling this flag来解决它,但我想避免它。

我也可以尝试手动将每个需要的方法和属性引用到内部匹配:re.Match 变量(也想避免这种情况)。

我正在寻找更“Pythonic”的解决方案。 有什么想法吗?

【问题讨论】:

  • 即使你可以从re.Match 继承,你也不能手动__init__re.Match() 说“不能创建're.Match' 实例”。那么,您如何想象得到这样的 Region 实例?

标签: python regex cpython


【解决方案1】:

我可能只使用一个简单的代理对象 á 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")

【讨论】:

  • 方法可以正常工作,因为它们是 Python 中的绑定方法。 region.group 为您提供已经绑定到内部 matchgroup 方法。
  • 这已经完成,但仍然是一种解决方法
猜你喜欢
  • 2018-08-24
  • 2016-05-29
  • 1970-01-01
  • 1970-01-01
  • 2018-03-10
  • 2012-07-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多