The following code:
class MyClass():
def test(self):
self.__x = 0
def __setattr__(self, name, value):
print name
def __getattr__(self, name):
print name
raise AttributeError(name)
x = MyClass()
x.test()
x.__y
Outputs:
_MyClass__x
__y
Traceback (most recent call last):
...
AttributeError: __y
The documentation is utterly unhelpful stating the “name” is the “name of the attribute”, yet for some reason it’s different depending on whether you are setting it or getting it.
What I want to know is:
- Am I doing something fundamentally wrong here?
- How do I get
xin the first case instead of_MyClass__x?
The double underscore invokes name mangling. If you don’t need name mangling, don’t use double undescore
What is the meaning of a single- and a double-underscore before an object name?
From the Python docs