 
 Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
Advertisements
                    