首页 > 解决方案 > 如果缺少属性,如何在类定义阶段引发错误

问题描述

使用下面的示例,我如何确保继承 的任何类AdderMixin都具有 property x。这将在类定义阶段完成。

class AdderMixin:
    x: int

    @classmethod
    def add(cls, other):
        return cls.x + other


class B(AdderMixin):
    x = 3


class C(AdderMixin):
    pass

# I would like an error to be raised by here, 
# as C inherited AdderMixin without defining x

print(B.add(4))
print(C.add(5))  # actually errors here.

标签: python

解决方案


推荐阅读