Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

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.

Updated on: 2020-06-15T10:56:42+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements