python - 禁止在 Python 中将类成员设置为 None
问题描述
Python中有没有办法禁止类成员被设置为 None 之外__init__
?
class Dummy:
def __init__(self, x):
if x is not None:
self.x = x
else:
raise Exception("x cannot be None")
d = Dummy("foo")
d.x = None
在我的代码中,我有类型提示,但这些不是强制的,所以说x
can only bestr
并没有真正改变任何允许的内容。
解决方案
你需要一个@property
:
class Dummy:
def __init__(self, x):
self.x = x
@property
def x(self):
return self._x
@x.setter
def x(self, value):
if value is None:
raise Exception("x cannot be None")
self._x = value
d = Dummy(8)
d.x = 16
d.x = None # Raises
推荐阅读
- sql - 如何提高获取记录的速度?
- java - 即时与 ZoneDateTime。转换到另一个时区
- javascript - 异步函数javascript不在后台运行?
- python - 在 M1 Mac 中安装 TensorFlow
- python - Sublime Text 3 - Conda:不显示包列表(在 Mac 上)
- javascript - Django在for循环外移动javascript代码和表单
- angular - 减速器的“开”有什么作用
- swift - Swift:尝试将记录推送到实体时,NSManaged 中出现“运算符后的预期表达式”错误
- php - 创建 HTTP Web 代理
- excel - Excel xlsm 文件宏未显示