python - 如果缺少属性,如何在类定义阶段引发错误
问题描述
使用下面的示例,我如何确保继承 的任何类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.
解决方案
推荐阅读
- android - Android Mapview 标记延迟
- python - IndexError:索引 2 超出轴 0 的范围,大小为 2 的矩阵不是正方形
- pyspark - 如何使用 pyspark graphframe pregel API 实现循环检测
- r - 许多列中的 str_replace 问题和
- reactjs - 无法在事件处理程序中获取更新的状态值
- scala - Spark使用wholeTextFiles获取行号zipWithIndex
- c# - mscorlib.dll、System.Data.dll 和 EntityFramework.dll 在输出窗口中引发的异常
- scheme - 方案:查找列表中大于 X 数的所有元素
- machine-learning - gamma和epsilon在KL散度计算中的作用是什么?
- python - 如何在 javascript 中检索 Python 数组(Flask 到 React 通信)