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 to share