Encapsulation

Encapsulation is one of the cornerstone concepts of OOP. The basic idea of Encapsulation is to wrap up both data and methods into one single unit. The way that data and methods are organized does not matter to the end-user. The user is only concerned about the right way to provide input and expects a correct output on the basis of the inputs provided.


Encapsulation in Python also ensures that objects are self-sufficient functioning pieces and can work independently.

Why do we need Encapsulation in Python?
The advantages of Encapsulation in Python can be summed up as follows –

1. Encapsulation provides well-defined, readable code
The primary advantage of using Encapsulation in Python is that as a user, we do not need to know the architecture of the methods and the data and can just focus on making use of these functional, encapsulated units for our applications. This results in a more organized and clean code. The user experience also improves greatly and makes it easier to understand applications as a whole.

2. Prevents Accidental Modification or Deletion
Another advantage of encapsulation is that it prevents the accidental modification of the data and methods. Let’s consider the example of NumPy again, if I had access to edit the library, then I might make a mistake in the implementation of the mean function and then because of that mistake, thousands of projects using NumPy would become inaccurate.

3. Encapsulation provides security
Encapsulation in Python is achieved through the access modifiers. These access modifiers ensure that access conditions are not breached and thus provide a great user experience in terms of security.

Access Modifiers in Python encapsulation

Sometimes there might be a need to restrict or limit access to certain variables or functions while programming. That is where access modifiers come into the picture.

Now when we are talking about access, 3 kinds of access specifiers can be used while performing Encapsulation in Python. They are as follows :

  • Public Members
  • Private Members
  • Protected Members
Posted on by