如果缺少属性,如何在类定义阶段引发错误

时间:2019-04-28 14:07:05

标签: python

使用下面的示例,如何确保继承AdderMixin的任何类都具有属性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.

0 个答案:

没有答案