What does double underscore prefix do in Python variables?

PythonServer Side ProgrammingProgramming

Double underscore prefix

In Python, we use double underscore i.e., __ before the attribute's name and those attributes will not be directly accessible/visible outside. Double underscore mangles the attribute's name. However, that variable can still be accessed using some tricky syntax but it's generally not a good idea to do so. Double underscores are used for fully private variables.

According to Python documentation

If your class is intended to be subclassed, and you have attributes that you do not want subclasses to use, consider naming them with double leading underscores and no trailing underscores. This invokes Python's name mangling algorithm, where the name of the class is mangled into the attribute name. This helps avoid attribute name collisions should subclasses inadvertently contain attributes with the same name. 

Example

The code below shows use of double underscore.

class MyClass:
    __hiddenVar = 0
    def add(self, increment):
       self.__hiddenVar += increment
       print (self.__hiddenVar)
myObject = MyClass()
myObject.add(3)
myObject.add (8)
print (myObject.__hiddenVar)

Output 

3
Traceback (most recent call last):
11
  File "C:/Users/TutorialsPoint1/.PyCharmCE2017.2/config/scratches/scratch_1.py", line 12, in <module>
    print (myObject.__hiddenVar)
AttributeError: MyClass instance has no attribute '__hiddenVar'

In the above program, we tried to access hidden variable outside the class using object and it threw an exception.

raja
Updated on 15-Jun-2020 11:02:02

Advertisements