📜  python 在子类中强制执行类变量 - Python 代码示例

📅  最后修改于: 2022-03-11 14:45:38.995000             🧑  作者: Mango

代码示例1
class Foo:

    page_name = None
    author = None

    def __init_subclass__(cls, **kwargs):
        for required in ('page_name', 'author',):
            if not getattr(cls, required):
                raise TypeError(f"Can't instantiate abstract class {cls.__name__} without {required} attribute defined")
        return super().__init_subclass__(**kwargs)


class Bar(Foo):
    page_name = 'New Page'
    author = 'eric'