具有公共getter和private setter的Python属性 [英] Python property with public getter and private setter

查看:101
本文介绍了具有公共getter和private setter的Python属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的python属性:

I have a python property like this:

class Foo:

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

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

当前,每个人都可以获取和设置maxInputs的值.

Currently, the value of maxInputs can be get and set by everyone.

但是,我希望所有人都可以获取maxInputs的值,但只能在Foo类的内部进行设置.

However, I want to allow everyone to get the value of the maxInputs, but it should only be set inside of the Foo class.

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

So is there a way to declare a property with a private setter and a public getter?

推荐答案

Python没有没有隐私模型.使用下划线只是一个约定,没有访问控制. 如果您不希望'public'API包含sett,则只需从类中删除setter并直接在类代码中将其分配给self._persistentMaxInputs.value即可.如果您想限制需要记住的位置数量,可以将其设为功能:

Python has no privacy model. Using underscores is only a convention, there is no access control. If you don't want the 'public' API to include a sett, then just remove the setter from your class and assign to self._persistentMaxInputs.value in your class code directly. You can make it a function if you want to limit the number of locations that need to remember this:

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

当然可以将其设为单独的property对象,但是随后您必须放弃装饰器语法:

You can of course make that a separate property object, but then you'd have to forgo the decorator syntax:

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

,但现在至少您可以在类代码中使用self._maxInputs = value.但是,这实际上并没有提供太大的语法改进.

but now at least you can use self._maxInputs = value in your class code. This doesn't really offer that much of a syntax improvement however.

这篇关于具有公共getter和private setter的Python属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆