Encapsulation means binding data and variables inside a class.This article will help you understand encapsulation concept with python implementation.As well as you will come to know encapsulation industrial use cases.
Python is an object-oriented programming language with classes and objects at its foundation. This article will focus on one of the most prominent OOPs concepts – Encapsulation. Encapsulation involves wrapping up the data, like code elements, into a single unit. Think of medicines in a pill or stationery items in your bag. Today, we will learn Encapsulation in Python. We will be covering the following sections:
- What is Encapsulation?
- Why use Encapsulation?
- How is Encapsulation used in the industry?
- Advantages of Encapsulation in Python
- How is Data Hiding Achieved in any Object-oriented Programming Language?
- Implementing Encapsulation in Python
What is Encapsulation?
Encapsulation is the process of bundling data members and methods inside a single class. Bundling similar data elements inside a class also helps in data hiding. Encapsulation also ensures that objects of a class can function independently.
Why use Encapsulation?
Consider an analogy of a car – I’m sure most of us enjoy going on long drives and generally enjoy driving our cars. We know how to change gears, use the steering wheel, apply breaks, or accelerate as and when required.
But not most of us need to know how cars are manufactured. We do not know how the parts were acquired or how long it took to design that model. All these factors are irrelevant to us, and what matters is the final product only.
This is basically how Encapsulation works – Python codes encapsulate and hide backend implementation details by restricting the permissions. However, this does not hinder the program’s execution in any manner. Thus, Encapsulation facilitates Data Abstraction.
Related Reads: Features of JAVA
The core idea behind this mechanism is simple. Suppose you have a variable that is not used on the outside of an object. It can be bundled with methods that provide read or write access. Encapsulation allows you to hide certain information and control access to the object’s internal state.
How is Encapsulation used in the industry?
Encapsulation is used with abstraction to define the level of access you want to give a user. Consider the following use cases:
Use Case 1: Login Verification
When you log in to check your mails on Gmail, yahoo mail, outlook, etc., you enter your password for logging. The password is then encrypted and verified, and access is granted on successful verification.
But being a user, you don’t know how your password is being verified in the backend, keeping your account safe. This is one of the many actual cases of how Encapsulation is used in the industry.
Use Case 2: Bank Account Balance
You don’t want your bank balance to be a piece of public information, right! This will be the case if the balance variable in the banking app is declared a public variable. And in this case, anyone could know your account balance. So, would you like it? Obviously, not!
So, to avoid this case, developers declare the balance variable as private to keep the details safe so that no one can see your account balance.
The person who wants to check his account balance will be authenticated. Only the authenticated users can access the private members defined inside that class. This private method would be an account verification method that will match your saved account number or userID and password in the database with the entered details (userID and password) for authentication.
|Programming Online Courses and Certification||Python Online Courses and Certifications|
|Data Science Online Courses and Certifications||Machine Learning Online Courses and Certifications|
Advantages of Encapsulation in Python
Following are the advantages of Encapsulation in Python:
- Protects an object from unauthorized access
- Prevents other classes from using the private members defined within the class
- Prevents accidental data modification by using private and protected access levels
- Helps to enhance security by keeping the code/logic safe from external inheritance.
- Bundling data and methods within a class makes code more readable and maintainable
How is Data Hiding Achieved in any Object-oriented Programming Language?
In any OOPs-based programming language, data hiding is achieved by declaring the data members (variables, methods, etc.) private. If the variable or method is declared private, no one can access them from outside the class.
Points to Remeber:
- Declare data members as private in the class to make it inaccessible outside.
- Encapsulation is a combination of data hiding and abstraction.
Encapsulation = Data Hiding + Abstraction
NOTE: Any component that follows data hiding along with abstraction is encapsulated.
Implementing Encapsulation in Python
Add a new feature in the HR Management System that shows an employee’s salary and the project they are working on.
For this, we will create a class Employee and add some attributes like name, ID, salary, project, etc. As per the requirement, let’s add two required features (methods) – show_sal() to print the salary and proj() to print the project working on.
class Employee:# constructordef __init__(self, name, id, salary, project):# data membersself.name = nameself.id = idself.salary = salaryself.project = project# method to print employee's detailsdef show_sal(self):# accessing public data memberprint("Name: ", self.name, 'Salary:', self.salary)def proj(self):print(self.name, 'is working on', self.project)# creating object of a classemp = Employee('James', 102, 100000, 'Python')# calling public method of the classemp.show_sal()emp.proj()
Output: Name:James Salary:100000 James is Working on Python
Now let’s use Encapsulation to hide an object’s internal representation from the outside and make things secure. Whenever we work in a team and deal with sensitive data, it’s not ideal to provide access to all variables used within the class.
So, we have talked a lot about securing using Encapsulation, but how? This is where access modifiers come into the picture.
Access Modifiers in Python
Encapsulation is achieved by declaring a class’s data members and methods as either private or protected. But in Python, we do not have keywords like public, private, and protected, as in the case of Java. Instead, we achieve this by using single and double underscores.
Access modifiers are used to limit access to the variables and methods of a class. Python provides three types of access modifiers public, private, and protected.
- Public Member: Accessible anywhere from outside the class.
- Private Member: Accessible within the class.
- Protected Member: Accessible within the class and its sub-classes.
class Employee:# constructordef __init__(self, name,id, salary, project):# data membersself.name = name #Public (accessible from outside and inside the class)self.id = id #Publicself._project = project #Protected (accessible within the class and its subclass)self.__salary = salary #Private (accessible only inside the class it is declared)
Public Members can be accessed from outside and within the class. Making it easy to access by all. By default, all the member variables of the class are public.
class Employee:# constructordef __init__(self, name, salary):# public data membersself.name = nameself.salary = salary# public instance methodsdef show_sal(self):# accessing public data memberprint("Name: ", self.name, 'Salary:', self.salary)# creating object of a classemp = Employee('James', 100000)# accessing public data membersprint("Name: ", emp.name, 'Salary:', emp.salary)
Output: Name:James Salary:100000
We can protect variables in the class by marking them private. To make any variable a private just add two underscores as a prefix at the start of its name. For example, __salary.
Private members are accessible only within the class and cannot be accessed from the objects of the class.
class Employee:# constructordef __init__(self, name, salary):# public data memberself.name = name# private memberself.__salary = salary# creating object of a classemp = Employee('James, 100000)# accessing private data membersprint('Salary:', emp.__salary)
NOTE: The output of the above code will throw an error, since we are trying to access a private variable that is hidden from the outside.
How to access private methods outside the class?
Add private members inside a public method
You can declare a public method inside the class which uses a private member and call the public method containing a private member outside the class.
class Employee:# constructordef __init__(self, name, salary):# public data memberself.name = name# private memberself.__salary = salary# public instance methodsdef show_sal(self):# private members are accessible from a classprint("Name: ", self.name, 'Salary:', self.__salary)# creating an object of a classemp = Employee('James', 100000)# calling public method of the classemp.show_sal()
Output: Name:James Salary:100000
Protected members are accessible within the class and also available to its sub-classes. To define a protected member, prefix the member name with a single underscore. For example, _project. This makes the project a protected variable that can be accessed only by the child class.
# base classclass Company:def __init__(self):# Protected memberself._project = "Python"# child classclass Employee(Company):def __init__(self, name):self.name = nameCompany.__init__(self)def show_sal(self):print("Employee name :", self.name)# Accessing protected member in child classprint("Working on project :", self._project)c = Employee("James")c.show_sal()# Direct access protected data memberprint('Project:', c._project)
Hope this article was helpful for you to understand Encapsulation in Python and how to implement it. The OOPs concepts – inheritance, abstraction, and Encapsulation are among the most frequently asked questions during interviews for Python-related roles. So, it’s important to have a good grasp of these concepts. If you seek to learn more about Python and practice Python programming, you can explore related articles here.
Top Trending Article
Top Online Python Compiler | How to Check if a Python String is Palindrome | Feature Selection Technique | Conditional Statement in Python | How to Find Armstrong Number in Python | Data Types in Python | How to Find Second Occurrence of Sub-String in Python String | For Loop in Python |Prime Number | Inheritance in Python | Validating Password using Python Regex | Python List |Market Basket Analysis in Python | Python Dictionary | Python While Loop | Python Split Function | Rock Paper Scissor Game in Python | Python String | How to Generate Random Number in Python | Python Program to Check Leap Year | Slicing in Python
Data Science Interview Questions | Machine Learning Interview Questions | Statistics Interview Question | Coding Interview Questions | SQL Interview Questions | SQL Query Interview Questions | Data Engineering Interview Questions | Data Structure Interview Questions | Database Interview Questions | Data Modeling Interview Questions | Deep Learning Interview Questions |
Download this article as PDF to read offlineDownload as PDF