- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What does double underscore prefix do in Python variables?
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.
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)
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.
- What is the meaning of single underscore prefix with Python variables?
- What does the '@' prefix do in PHP?
- What does ** (double star) and * (star) do for parameters in Python?
- What does the @ prefix do on string literals in C#?
- What does the Double Star operator mean in Python?
- How does underscore "_" work in Python files?
- Underscore(_) in Python
- What does % do to strings in Python?
- What does reload() function do in Python?
- What does method time.tzset() do in Python?
- What does raw_input() function do in python?
- What does input() function do in python?
- What does print() function do in Python?
- What does open() function do in Python?
- What does close() function do in Python?