How can I reach a private variable within the object

前端 未结 3 887
慢半拍i
慢半拍i 2021-01-20 10:06

I would like to modify an object private variable

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


        
3条回答
  •  滥情空心
    2021-01-20 11:12

    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)

提交回复
热议问题