Python 属性 与 public getter 和私人 setter

Python property with public getter and private setter

我有一个 python 属性 这样的:

class Foo:

    @property
    def maxInputs(self):
        return self._persistentMaxInputs.value

    @maxInputs.setter
    def maxInputs(self, value):
        self._persistentMaxInputs.value = value

目前maxInputs的值可以被大家获取和设置。

但是,我想让大家得到maxInputs的值,但是应该只设置在Foo里面 class.

那么有没有办法用私有 setter 和 public getter 来声明 属性?

Python没有隐私模型。使用下划线只是一种约定,没有访问控制。 如果您不希望 'public' API 包含设置,则只需从 class 中删除 setter 并分配给 self._persistentMaxInputs.value 28=]直接代码。如果你想限制需要记住的位置的数量,你可以把它做成一个函数:

def _setMaxInputs(self, value):
    self._persistentMaxInputs.value = value

可以 当然可以将其作为一个单独的 property 对象,但是你必须放弃装饰器语法:

def _maxInputs(self, value):
    self._persistentMaxInputs.value = value
_maxInputs = property(None, _maxInputs)

但现在至少您可以在 class 代码中使用 self._maxInputs = value。然而,这并没有真正提供那么多的语法改进。

我在 public 属性 和私有 setter 的情况下使用两个属性。它确实创建了一些冗余代码,但我最终还是遵循了装饰器的约定。请参见下面的示例:

@property
def current_dir(self) -> str:
    """
    Gets current directory, analogous to `pwd`
    :return: Current working directory
    """
    return self._current_dir

@property
def _current_dir(self) -> None:
    return self._current_dir

@_current_dir.setter
def _current_dir(self, path:str) -> None:
    self._current_dir = path