本文介绍了我如何到达对象内的私有变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想修改对象私有变量

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?

推荐答案

从外部访问:

e = Example()
e._Example__myTest1   # 1

由于私有变量名称修改规则.

但是,如果您需要访问私有成员,则表明您的设计有问题.

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)

这篇关于我如何到达对象内的私有变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 10:42