简体   繁体   English

Python中成员变量的Getter和Setter

[英]Getter and Setter for member variable in Python

I know that it is not recommended to write getter and setter for class member variables in Python. 我知道不建议在Python中为类成员变量编写getter和setter方法。 Still I need to do it because I have a complex object which internally contains a lot of objects in depth. 仍然需要这样做,因为我有一个复杂的对象,内部包含许多深度的对象。 I need to expose a property/function in container object that will get and/or set member of inner object. 我需要在容器对象中公开将获取和/或设置内部对象成员的属性/函数。 How can I do this in Python? 如何在Python中执行此操作?

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

Above given function can act as a getter and setter but the syntax to use it would be confusing. 上面给出的函数可以充当getter和setter,但是使用它的语法会造成混淆。 My requirement is that user should get its value without using parenthesis and to set values he should pass parameters. 我的要求是,用户应在不使用括号的情况下获取其值,并设置值应传递参数。 Something like this 像这样

objectname.responseoperationcode ##this should return the value

and

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

Please suggest. 请提出建议。

Python supports properties . Python支持属性 You can change your code to: 您可以将代码更改为:

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

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

Now you can use the responseoperationcode function like a field, eg: 现在,您可以像字段一样使用responseoperationcode函数,例如:

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

Well, if you have access to the definition of the inner objects, you could write a getter method there. 好吧,如果您可以访问内部对象的定义,则可以在其中编写一个getter方法。 Then whole thing would look similar to this: 然后整个事情看起来像这样:

class OuterObject:
    innerObject        

    def getInnerField(self, field=None):
        if field == None: 
            return self.innerObject.getField()
        else:
            self.innerObject.setField(field)



class InnerObject:
    field

    def getField(self):
        return self.field

    def setField(self, field):
        self.field = field

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM