What is Encapsulation in Python?



Encapsulation is one of the key concepts of object-oriented languages like Python, Java, etc. Encapsulation is used to restrict access to methods and variables. In encapsulation, code and data are wrapped together within a single unit from being modified by accident.

Encapsulation is a mechanism of wrapping the data (variables) and code acting on the data (methods) together as a single unit. In encapsulation, the variables of a class will be hidden from other classes, and can be accessed only through the methods of their current class.

Encapsulation Example

Let’s say we have a company selling courses to students, engineers and professionals. The different sections of this company include, operations, finance, accounts, sales, etc. Now, if an employee from the accounts section needs the records of sales in 2022, then he/ she cannot directly access it.

To access, the employee of the account sections needs to get permission from the sales section team member. Therefore, the sales data is hidden from other departments, In the same way, the financials of the company is accessible to only the finance data and is hidden from other sections. The accounts, sales, finance, operations, marketing, etc. data is hidden from other sections

Implement Encapsulation with a Class in Python

Another example of Encapsulation can be a class because a class combines data and methods into a single unit. Here, the custom function demofunc() displays the records of students wherein we can access public data member. Using the objects st1, st2, st3, st4, we have access ed the public methods of the class demofunc()

Example

class Students: def __init__(self, name, rank, points): self.name = name self.rank = rank self.points = points # custom function def demofunc(self): print("I am "+self.name) print("I got Rank ",+self.rank) # create 4 objects st1 = Students("Steve", 1, 100) st2 = Students("Chris", 2, 90) st3 = Students("Mark", 3, 76) st4 = Students("Kate", 4, 60) # call the functions using the objects created above st1.demofunc() st2.demofunc() st3.demofunc() st4.demofunc()

Output

I am Steve
I got Rank  1
I am Chris
I got Rank  2
I am Mark
I got Rank  3
I am Kate
I got Rank  4

Python Access Modifiers

Let us see the access modifiers in Python to understand the concept of Encapsulation and data hiding 

  • public
  • private
  • protected

The public Access Modifier

The public member is accessible from inside or outside the class.

The private Access Modifier

The private member is accessible only inside class. Define a private member by prefixing the member name with two underscores, for example 

__age

The protected Access Modifier

The protected member is accessible. from inside the class and its sub-class. Define a protected member by prefixing the member name with an underscore, for example 

_points

Advertisements