Encapsulation In Python with examples

By

 Encapsulation:-

  • Encapsulation is a important concept of object oriented programming language.
  • In encapsulation methodology we can restrict access to methods and variables.
  • To prevent the data access of the class from out side or same class, is known as encapsulation.
  • In python ,we denote private attributes using prefix underscore(single(_) or double(__)).
  • It is used to hide the entire class data from the outside source. 
Benefits and needs of Encapsulation in python:-
  • Encapsulation concepts not only ensure better data flow but also protects the data from the outside sources.
  • Encapsulation is helpful to achieving well -defined interaction in each applications.
  • Encapsulation helps to secure the python applications.
  • Encapsulation ensures the data security and avoids the access the data accidentally.
Python allows us to access the method and variables from the outside the class as given below:-
e.g.
class rectangle:
    def __init__(self,a,b):
        self.height=a
        self.width=b
    def display(self):
        print("Rectangle height =",self.height)
        print("Rectangle width =",self.width)
rect=rectangle(20,30)
rect.display()
print("")
print("Changing the class variables values from outside the class:")
print("")
rect.height=50
rect.width=70
rect.display()
Output:-
Rectangle height = 20
Rectangle width = 30

Changing the class variables values from outside the class:

Rectangle height = 50
Rectangle width = 70
>>> 

Descriptions:-
  • In above example , i have updated the class variables height and width from the outside of the class.
  • Here any user can update the method and variable from the outside of the class.
e.g.
class rectangle:
    def __init__(self,a,b):
        self.height=a
        self.width=b
    def set_data(self,c,d):
        self.height=c
        self.width=d
    def rectangle_area(self):
        return (self.height*self.width)
rect=rectangle(40,50)
print(rect.rectangle_area())
print("After changing the width and height variables...")
rect.set_data(20,30)
print(rect.rectangle_area())
Output:-
2000
After changing the width and height variables...
600
>>> 
Method to Control Access:-
There are multiple methods in python to control access the variables from the outside of the class. 
  1. Using single underscore(_)
  2. Using Double underscore(__)
  3. Using Getter and Setter methods to access the private variables.
     1.) Using single underscore(_) :- In python programming conversion,To define private variables we generally use prefix with an underscore.If we use single under score with python variables.The variables are accessible as usual as before.This single underscore provide partial security in python.
e.g.   
class rectangle:
    def __init__(self,a,b):
        self._height=a
        self._width=b
    def display(self):
        print("Rectangle height =",self._height)
        print("Rectangle width =",self._width)
rect=rectangle(20,30)
rect.display()
print("")
print("Changing the class variables values from outside the class")
print("")
rect._height=50
rect._width=70
rect.display()
Output:-
Rectangle height = 20
Rectangle width = 30

Changing the class variables values from outside the class

Rectangle height = 50
Rectangle width = 70
>>> 
Description:-
There is no change in output after changing the single underscore in height and width variables in above program.
     2.) Using Double underscore:- When we put double underscore with variables in python.Python treats it as a private variables.We can't access it from the outside of the class.But single underscore is not a fully private variables in pthon.
e.g.   
class rectangle:
    def __init__(self,a,b):
        self.__height=a
        self.__width=b
    def display(self):
        print("Rectangle height =",self.__height)
        print("Rectangle width =",self.__width)
rect=rectangle(20,30)
rect.display()
print("")
print("Changing the value of class variable __width from outside of the class ")
print("")
rect.__width=70
rect.display()
print("Accessing the __height variable from outside of the class")
print(rect.__height)
Output:-
Rectangle height = 20
Rectangle width = 30

Changing the value of class variable __width from outside of the class 

Rectangle height = 20
Rectangle width = 30
Accessing the __height variable from outside of the class
Traceback (most recent call last):
  File "C:\Users\RAMASHANKER VERMA\Desktop\encapsulation1.py", line 16, in <module>
    print(rect.__height)
AttributeError: 'rectangle' object has no attribute '__height'
Description:-
  • First,I want to change the value of __width variable from outside of the rectangle class but it is unchanged because __width is a private variable of the rectangle class.
  • Second,I want to access the value of __height variable from outside of the rectangle class.I shows an error message because private variables can not access from outside of the class.
     3.) Using Getter and Setter methods to access the private variables:-
We can easily access the private variable using Getter and Setter method in python as given below:-
e.g.
class rectangle:
    def __init__(self,a,b):
        self.__height=a
        self.__width=b
    def set_height(self,c):
        self.__height=c
    def get_height(self):
        return self.__height
    
    def set_width(self,d):
        self.__width=d
    def get_width(self):
        return self.__width
    
    def rectangle_area(self):
        return (self.__height*self.__width)
rect1=rectangle(40,50)
rect1.set_height(90)
rect2=rectangle(20,30)
rect2.set_width(60)
print("Area of first rectangle is: ",rect1.rectangle_area())
print("Area of second rectangle is: ",rect2.rectangle_area())
#we can't access the __width value from the outside of the class because it is a private variable.
print(rect2.__width)  
Output:-
Area of first rectangle is:  4500
Area of second rectangle is:  1200
Traceback (most recent call last):
  File "C:\Users\RAMASHANKER VERMA\Desktop\encapsulation3.py", line 24, in <module>
    print(rect2.__width)
AttributeError: 'rectangle' object has no attribute '__width'
>>> 
Descriptions:-
  • In this example we can update the variables values using  Getter and Setter methods without any error.
  • In above program,we can't access the  __width variable from the outside of the class.Because __height and __width both are private variables of the rectangle class.
Second example of Getter and Setter method:-
e.g.
class number():
    a=5
    _b=10
    __c=40
    def set_data(self,p):
       self.__c=p
    def get_data(self):
      return self.__c
n=number()
n.set_data(30)
print(n.a)
print(n._b)
print(n.get_data())
print(n.__c)
Output:-
5
10
30
Traceback (most recent call last):
  File "C:\Users\RAMASHANKER VERMA\Desktop\encapsulation4.py", line 14, in <module>
    print(n.__c)
AttributeError: 'number' object has no attribute '__c'
>>> 
To access the Private Methods and variables from the outside of the class:
We can access the private method from the outside of the class using two ways:-
  1. By using Public Method concepts
  2. By using Name Mangling concepts
1.) Access the private methods and variables using public method:-
You access the private methods and variables in python by using public method in the class.I have explained it with an example as given below:-
e.g.
class ABC:
    #declaring public method
    def rectangle(self):
        print("I am public class method")
    #declaring private method    
    def __square(self):
        print("I am private class method")
    #calling the private method via another public method
    def calculate(self):
        self.rectangle()
        self.__square()
#creating object of the class
obj1=ABC()
obj1.calculate()
obj1.rectangle()
Output:-
I am public class method
I am private class method
I am public class method
>>> 
2.) Access the private methods and variables by using Name Mangling concept:-
We can access the private methods and variables by using Name Mangling concept in python as given below:-
Syntax:- 
obj._classname__identifierName
In below example, i have used Name Mangling obj._ABC__fun() and   obj._ABC__a concepts to access the private variables in ABC class. 
e.g. 
class ABC:
    __a=5
    #declaring public method
    def fun (self):
        print("I am public class method")
    #declaring private method    
    def __fun1(self):
        print("I am private class method")
      
#creating object of the class
obj=ABC()
obj.fun()
#calling the private method through name mangling
obj._ABC__fun1()
print(obj._ABC__a)
Output:-
I am public class method
I am private class method
5
>>>
Descriptions:-
In below example, i have used Name Mangling concepts  obj._ABC__fun() to access the private method and   obj._ABC__a to access the private variables in ABC class.
Watch complete Lecture video:-
------------coming soon---------------
For More...

0 comments:

Post a comment

Powered by Blogger.