代码之家  ›  专栏  ›  技术社区  ›  Neil G

我能写abc吗。在Python 3.6中不使用元类的ABC?

  •  1
  • Neil G  · 技术社区  · 7 年前

    Python 3.6 PEP 487 ,这增加了一个 __init_subclass__ 方法等等。是否可以编写一个版本的 ABC

    1 回复  |  直到 7 年前
        1
  •  3
  •   flornquake    6 年前

    如果你所关心的只是检查抽象方法,那么是的。只需移动 abstract method set computation __init_subclass__

    def __init_subclass__(cls, **kwargs):
        super().__init_subclass__(**kwargs)
        # Compute set of abstract method names
        abstracts = {name
                     for name, value in vars(cls).items()
                     if getattr(value, "__isabstractmethod__", False)}
        for base in cls.__bases__:
            for name in getattr(base, "__abstractmethods__", set()):
                value = getattr(cls, name, None)
                if getattr(value, "__isabstractmethod__", False):
                    abstracts.add(name)
        cls.__abstractmethods__ = frozenset(abstracts)
    

    基地 object.__new__ implementation 然后使用非空 __abstractmethods__ 设置为防止实例化。

    virtual subclass registration ; 这个 two hook methods this requires