
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
How data hiding works in Python Classes?
Data hiding
In Python, we use double underscore before the attributes name to make them inaccessible/private or to hide them.
The following code shows how the variable __hiddenVar is hidden.
Example
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/~_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.
We can access the value of hidden attribute by using a special syntax as follows −
Example
class MyClass: __hiddenVar = 12 def add(self, increment): self.__hiddenVar += increment print (self.__hiddenVar) myObject = MyClass() myObject.add(3) myObject.add (8) print (myObject._MyClass__hiddenVar)
Output
15 23 23
Private methods can be accessed from outside their class, but not as easily as in normal cases. Nothing in Python is truly private; internally, the names of private methods and attributes are mangled and unmangled on the fly to make them inaccessible by their given names.
- Related Articles
- Data Hiding in Python
- Data Classes in Python (dataclasses)
- What is Data Hiding in Python Object Oriented Programming?
- Hiding specific data in HANA Modeling View
- Difference Between Abstraction and Data Hiding
- Difference Between Data Hiding and Encapsulation
- Golang program to show data hiding in class
- Hiding a column in Data Preview in SAP HANA
- How to define classes in Python?
- How regular expression grouping works in Python?
- How variable scope works in Python function?
- How does == operator works in Python 3?
- How to use enums in Python classes?
- How do Python Dictionary Searching works?
- How regular expression back references works in Python?

Advertisements