python - Python 中成员变量的 Getter 和 Setter

标签 python

我知道Python不推荐给类成员变量写getter和setter。我仍然需要这样做,因为我有一个复杂的对象,它内部包含很多深度对象。我需要在容器对象中公开一个属性/函数,它将获取和/或设置内部对象的成员。我如何在 Python 中执行此操作?

def responseoperationcode(self,operationcode=None):
    if operationcode:
        self.innerobject.operationcode=operationcode
    else:
        return self.innerobject.operationcode

上面给定的函数可以充当 getter 和 setter,但使用它的语法会令人困惑。我的要求是用户应该在不使用括号的情况下获取它的值,并设置他应该传递参数的值。像这样

objectname.responseoperationcode ##this should return the value

objectname.responseoperationcode("SUCCESS")##this should set the value

请提出建议。

最佳答案

Python 支持 properties .您可以将代码更改为:

@property
def responseoperationcode(self):
    return self.innerobject.operationcode

@responseoperationcode.setter    
def responseoperationcode(self, value):    
    self.innerobject.operationcode = value

现在你可以像字段一样使用responseoperationcode函数,例如:

objectname.responseoperationcode # this returns the value
objectname.responseoperationcode = "SUCCESS" # this sets the value

关于python - Python 中成员变量的 Getter 和 Setter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21376347/

相关文章:

Python:在单行中打破for循环 for loop & performance of single line vs block-code

python - 如何在 Python 中重复字符串中的单个字符

python - 重新排序 Django 模型中的字段

python - 如何用 Python 解决这个数学难题?

python - 操作系统错误 : Could not open VISA library

python - Python中的二分查找,更优雅的方法?

python - + : 'WindowsPath' and 'str' 不支持的操作数类型

python - numpy.max 还是 max ?哪个更快?

python - 使用列表中的值以交互方式设置变量

python - 在 scikit-learn 中使用 python 生成器