How can I reach a private variable within the object

一曲冷凌霜 提交于 2019-12-31 01:50:08

问题


I would like to modify an object private variable

class Example():
    __myTest1 = 1
    __myTest2 = 1
    def __init__(self):
        pass
    def modifyTest(self, name = 'Test1', value):
        setattr(self, '__my'+name, value);

I tried the code above and it's seems that not possible to reach a private variable,

AttributeError: Example instance has no attribute '__myTest1'

Is there any way to modify a private variable?


回答1:


Accessing from outside:

e = Example()
e._Example__myTest1   # 1

Due to private variable name mangling rules.

But if you need to access private members, it is an indication of something wrong in your design.

If you need to access or update it from within the class itself:

class Example():
    __myTest1 = 1
    __myTest2 = 1
    def __init__(self):
        pass

    @classmethod
    def modifyTest(cls, value, name="Test1"):
        setattr(cls, '_%s__my%s' % (cls.__name__, name), value)

This must be done because it is a private class-static variable and not a private instance variable (in which case it would be straightforward)




回答2:


Try adding a single underscore and the class name to the beginning of the variable.

def modifyTest(name = 'Test1', value):
    setattr(self, '_Example__my' + name, value)



回答3:


class Example():
    __myTest1 = 1
    __myTest2 = 1
    def __init__(self):
        pass
    def modifyTest(self, name, value):
        setattr(self, '__my'+name, value)

Optional variables must come after mandatory variables.



来源:https://stackoverflow.com/questions/9990454/how-can-i-reach-a-private-variable-within-the-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!