The encapsulation in python means wrapping the data members and member functions in a single block of code. Encapsulation protects the wrapped data by directly accessing the data from outside the class. In simple words, data encapsulation in python provides high-level security to the data stored in the class.
Table of Contents
How to achieve encapsulation in python?
To achieve encapsulation in python, we need to declare the data members as private or protected so no one can access it from outside.
To declare the data members and function as private, simply add a double underscore before its name.
To declare the data members and function as protected, add a single underscore before its name.
encapsulation in python with example
Encapsulation using private data members
Example
class rectangle:
__length = 0 #private data member
__breadth = 0 #private data member
def __init__(self,len,bre): #Constructor
self.__setlenght(len)
self.__setbreadth(bre)
def __setlenght(self,len): #private member function
self.__length = len #assigning value to the private data member
def __setbreadth(self,bre): #private member function
self.__breadth = bre #assigning value to the private data member
def area(self):
area = self.__length * self.__breadth #calculating area
return area # returning area
len = int(input("Enter length: ")) #Accepting data from user
bre = int(input("Enter Breadth: ")) #Accepting data from user
obj = rectangle(len,bre) # creating object and passing values to its constructor
area = obj.area() #calling area function
print("The area of the rectangle is: ",area)
obj.__setlength() #this function in not accessible
obj.__setbreadth() #this function in not accessible
Output
Enter length: 20
Enter Breadth: 30
The area of the rectangle is: 600
Traceback (most recent call last):
File "encapsulation.py", line 24, in <module>
obj.__setlength() #this function in not accessible
AttributeError: 'rectangle' object has no attribute '__setlength'
Traceback (most recent call last):
File "encapsulation.py", line 25, in <module>
obj.__setbreadth() #this function in not accessible
AttributeError: 'rectangle' object has no attribute '__setbreadth'
Encapsulation using protected data members –
Example
class square:
_side = 0 #protected data member
def __init__(self,side): #Constructor
self._setside(side)
def _setside(self,side): #protected member function
self._side = side #assigning value to the protected data member
def area(self):
area = self._side * self._side #calculating area
return area # returning area
side = int(input("Enter side of the square: "))
obj = square(side) # creating object and passing values to its constructor
area = obj.area() #calling area function
print("The area of the square is: ",area)
Output
Enter side of the square: 15
The area of the square is: 225