Encapsulation in Python
Encapsulation is one of the basic principles of Object Oriented Programming. Simply speaking, encapsulation means we are bundling the data, and the functions to access the data into a single unit. When we will try an example for understanding the concept of encapsulation, we will get a broad idea. But here, we are simply going to have some data, that we cannot directly access. There would be some method, with which, we can access that data member.
The encapsulation is also referred to as Data hiding. We can simply say that we are putting some restrictions on accessing the members directly and making any unexpected changes. We will make such arrangements, that the data can be only changed using the object methods.
Encapsulation in Python
Let’s consider a very dummy example for understanding what is going to happen. For example, you have created an account on some social media platform, and you have given some of your details, like your name, email address, mobile number, and some other details. Now, Let’s consider that account as the object, and the data that you have provided, as the attributes, and there are some methods, with which, you can do different things.
Now, Let’s say that this account is associated with the email address, and you are not supposed to change that. To avoid this unexpected change, there is some restriction on what you can change, and what you cannot. Like you can change your profile picture associated with that account, but you cannot change the email address associated with that account.
So, in such situations, we have to have the data such that it cannot be directly accessed, and rather we have some methods, which would be used to access that data. (The access also may not be direct, like if you want to access your bank balance, which of course should not be accessed directly, you will have to validate the transaction first, and then you would be able to view your account balance).
So, Let’s now try to have a look at a simple example, to understand the concept of encapsulation. There are some basic things here, that we are going to need like we are going to need to make the variables private so that we cannot access them directly, and then we would need some method, using which, we would access the data.