How can I get a private variable inside an object

I would like to change a private variable of an object

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

      

I have tried the code above and it seems that it is not possible to get the private variable,

AttributeError: Example instance has no attribute '__myTest1'

      

Is there a way to change a private variable?

+3


source to share


3 answers


External access:

e = Example()
e._Example__myTest1   # 1

      

Due to the private variable of the name change rule .

But if you need to access private members, that would be a sign of something wrong with your design.



If you need to access or update it from 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 needs to be done because it is a private static class variable, not a private instance variable (it would be easy in that case)

+6


source


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



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

      

+1


source


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

      

Optional variables must appear after required variables.

0


source







All Articles