Getter和Setter用于Python中的成员变量

gli*_*81g 1 python

我知道不建议在Python中为类成员变量编写getter和setter.我仍然需要这样做,因为我有一个复杂的对象,内部包含很多深度的对象.我需要在容器对象中公开一个属性/函数,它将获取和/或设置内部对象的成员.我怎么能用Python做到这一点?

def responseoperationcode(self,operationcode=None):
    if operationcode:
        self.innerobject.operationcode=operationcode
    else:
        return self.innerobject.operationcode
Run Code Online (Sandbox Code Playgroud)

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

objectname.responseoperationcode ##this should return the value
Run Code Online (Sandbox Code Playgroud)

objectname.responseoperationcode("SUCCESS")##this should set the value
Run Code Online (Sandbox Code Playgroud)

请建议.

slo*_*oth 8

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

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

@responseoperationcode.setter    
def responseoperationcode(self, value):    
    self.innerobject.operationcode = value
Run Code Online (Sandbox Code Playgroud)

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

objectname.responseoperationcode # this returns the value
objectname.responseoperationcode = "SUCCESS" # this sets the value
Run Code Online (Sandbox Code Playgroud)