When many C++ and Java programmers first learn Python, they are surprised by Python's lack of a private
keyword. The nearest concept is 'name mangling'. Every time an attribute is prefixed by "__
", it is renamed by the interpreter on the fly:
>>> class MyClass(object): ... __secret_value = 1 ... >>> instance_of = MyClass() >>> instance_of.__secret_value Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'MyClass' object has no attribute '__secret_value' >>> dir(MyClass) ['_MyClass__secret_value', '__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__'] >>> instance_of._MyClass__secret_value 1
This is provided to avoid name collision under inheritance, as the attribute is renamed with the class name as a prefix. It is not...