首页 > 解决方案 > 禁止在 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

在我的代码中,我有类型提示,但这些不是强制的,所以说xcan only bestr并没有真正改变任何允许的内容。

标签: python

解决方案


你需要一个@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

推荐阅读