What is the meaning of single underscore prefix with Python variables?

PythonServer Side ProgrammingProgramming

Single Underscore

Names, in a class, with a leading underscore are basically to indicate to other programmers that the attribute or method is intended to be private. 

It is recommended to use single underscores for semi-private and double underscores for fully private variables.

To quote PEP-8 −

 _single_leading_underscore: weak "internal use" indicator. E.g. from M import * does not import objects whose name starts with an underscore.


The following code shows difference between double and single underscore prefixes

class MyClass():
     def __init__(self):
             self.__fullrprivate = "World"
             self._semiprivate = "Hello"
mc = MyClass()
print mc._semiprivate
print mc.__fullprivate


Traceback (most recent call last):
File "C:/Users/TutorialsPoint1/~_1.py", line 8, in <module>
print mc.__fullprivate
AttributeError: MyClass instance has no attribute '__fullprivate'

Published on 19-Jan-2018 12:32:16