Encapsulation in Python
Encapsulation is one of the critical features of object-oriented programming, which involves the bundling of data members and functions inside a single class. Bundling similar data members and functions inside a class also helps in data hiding. Encapsulation also ensures that objects are self-sufficient functioning pieces and can work independently.
What is Encapsulation in Python?
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.
4. Encapsulation provides reusability
It is easier to reuse code when it is encapsulated. Creating objects that contain common functionality allows us to reuse them in many settings.
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
Encapsulation in Python using public members
As the name suggests, the public modifier allows variables and functions to be accessible from anywhere within the class and from any part of the program. All member variables have the access modifier as public by default.
Now let’s check out how we can implement Encapsulation in Python using public methods –
Evidently, from the above code, you can make out that we declared two variables and two methods of the class pub_mod. We were able to access the variables and methods wherever we wanted with ease as the access modifier for them was public, which means they should be accessible everywhere.
This claim is satisfied as we can see in the output –
Encapsulation in Python using private members
The private access modifier allows member methods and variables to be accessed only within the class. To specify a private access modifier for a member, we make use of the double underscore __.
Let’s check out this example to understand how we can implement Encapsulation using private members –
We have accessed len both within and outside the class in the above snippet. Let’s see what kind of output that gives us.
We can see that we have received an AttributeError in the output. Can you guess why?
Well, your thoughts should wander towards the private access modifier!
Since len is a private member and we have tried to access it outside the class, that is why we received the above error. We can access private members from outside of a class using the following two approaches
- Public method to access private members
- Name Mangling to access private members
Public method to access private members
Name Mangling to access private members
We can directly access private and protected variables from outside of a class through name mangling. The name mangling is created on an identifier by adding two leading underscores and one trailing underscore, like this _classname__dataMember, where classname is the current class, and data member is the private variable name.
Encapsulation in Python using protected members
What sets protected members apart from private members is that they allow the members to be accessed within the class and allow them to be accessed by the sub-classes involved. In Python, we demonstrate a protected member by prefixing with an underscore _ before its name.
As we know, if the members have a protected access specifier, it can also be referenced then within the class and the subsequent sub-clas
So now let’s see this concept in action –
It is quite clear from the output that the class pro_mod was successfully able to inherit the variables from the class details and print them to the console, although they were protected variables. And when we tried to refer to them outside of their parent class and the sub-class, we got an AttributeError for the same.
Advantages of Encapsulation
Code reusability: Encapsulation in Python allows developers to create reusable code by hiding the implementation details of an object or class and only exposing a public interface for interacting with it.
Data hiding: Encapsulation helps to protect the internal state of an object or class from being accessed or modified by external code, which improves the security of the application.
Improved maintainability: By encapsulating the implementation details of an object or class, developers can make changes to the internal state or behavior of the object without affecting external code that uses it.
Easier to understand: Encapsulation makes the code more organized and easier to understand by clearly separating the public interface from the implementation details.
Better control over class properties: Encapsulation allows developers to have better control over the properties and methods of a class, by making some properties private or protected and only allowing them to be accessed by specific methods.
Better class design: Encapsulation encourages developers to design classes that are cohesive and have a single responsibility, which makes the code more modular and easier to maintain.
You have finally reached the end of this article and successfully learned everything about one of the most important fundamental concepts of Object-Oriented Programming!
In this article, we covered –
Encapsulation in Python refers to the practice of hiding the implementation details of an object or class, and only exposing a public interface for interacting with it.
Encapsulation is achieved through the use of access modifiers such as 'public', 'private', and 'protected'.
Variables and methods declared with the 'private' or 'protected' access modifiers are not accessible from outside the class, while those declared as 'public' are.
Encapsulation helps to promote code reusability, maintainability, and security by preventing external code from accessing or modifying the internal state of an object or class.
The '_' or '__' prefix can be used to indicate a variable or method as private, however, it is not enforced by the interpreter and can still be accessed.
Encapsulation is a key concept in object-oriented programming and is used in many popular Python libraries and frameworks.
In Python, encapsulation is not as strict as in other languages such as Java, as it does not have the concept of protected variables and methods.