Quantcast
Channel: JS Tricks » Python
Viewing all articles
Browse latest Browse all 25

Python Data hiding tutorial – Python OOP Lesson

$
0
0

Data hiding and encapsulation both are much less the same. In this tutorial we will learn about Python Data Hiding.

Python Data hiding

In Python sometime you will want to hide the object’s attributes outside the class definition. For that, you can use double underscore before the attributes name and those attributes will not be directly visible outside.

Example

Here is an example regarding Python Data Hiding:

class MyClass:
   __hiddenVariable = 0
  
   def add(self, increment):
      self.__hiddenVariable += increment
      print self.__hiddenVariable

myObject = MyClass()
myObject.add(2)
myObject.add(5)
print myObject.__hiddenVariable

When you run the script the output will be like this:

2
7
Traceback (most recent call last):
  File "main.py", line 13, in 
    print myObject.__hiddenVariable
AttributeError: MyClass instance has no attribute '__hiddenVariable'

You see that __hiddenVariable is not accessible. Actually, Python protects the members by internally changing the names to include the class name. You can access these attributes as objectName._className__attributeName.

If we write the code like this:

class MyClass:
   __hiddenVariable = 0
  
   def add(self, increment):
      self.__hiddenVariable += increment
      print self.__hiddenVariable

counter = MyClass()
counter.add(2)
counter.add(5)
print counter._MyClass__hiddenVariable

Then we will see that the output shows :

2
7
7

 

The post Python Data hiding tutorial – Python OOP Lesson appeared first on JS Tricks.


Viewing all articles
Browse latest Browse all 25

Trending Articles