Encapsulation in Python

Encapsulation in Python

7 mins read3.7K Views Comment
Updated on Oct 12, 2023 17:26 IST

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.

2022_07_pp.jpg

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?

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.

2022_07_image-179.jpg

To understand Encapsulation, you should have a working knowledge of the following concepts in Python:

How to Check if Two Python Strings are Anagrams
How to Check if Two Python Strings are Anagrams
An Anagram is a word or phrase that is formed by rearranging all the letters of a different word or phrase exactly once such as elbow and below. In this...read more
Python Sorted() Function
Python Sorted() Function
The sorted() function is designed to return a new sorted list from the items in an iterable. Whether you're dealing with numbers, strings, or custom objects, sorted() can handle it...read more
Ternary Operators in Python
Ternary Operators in Python
For a Python programmer, one of the major concerns is the size and readability of the code. Any efficient program in Python is supposed to be easily readable, short, and...read more
Recommended online courses

Best-suited Python courses for you

Learn Python with these high-rated online courses

Free
6 weeks
– / –
2 weeks
– / –
16 weeks
1.7 K
3 months
– / –
– / –
4.24 K
2 weeks
3 K
3 weeks
– / –
4 months

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.

What is Programming What is Python
What is Data Science What is Machine Learning

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 

2022_07_image-136.jpg

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

2022_07_image-137.jpg

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

Problem Statement: 

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:
# constructor
def __init__(self, name, id, salary, project):
# data members
self.name = name
self.id = id
self.salary = salary
self.project = project
# method to print employee's details
def show_sal(self):
# accessing public data member
print("Name: ", self.name, 'Salary:', self.salary)
def proj(self):
print(self.name, 'is working on', self.project)
# creating object of a class
emp = Employee('James', 102, 100000, 'Python')
# calling public method of the class
emp.show_sal()
emp.proj()
Copy code
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.

Top 110+ Python Interview Questions and Answers
Top 110+ Python Interview Questions and Answers
Python is a widely-used general-purpose, object-oriented, high-level programming language. It is used to create web applications, and develop websites and GUI applications. The popularity of the language is due to...read more
Pandas Interview Questions for Data Scientists
Top 9 NumPy Interview Questions
Top 9 NumPy Interview Questions
In this article, we will discuss basic and intermediate NumPy Interview Questions in most simplified ways with example.

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 publicprivate, 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.

Example:


 
class Employee:
# constructor
def __init__(self, name,id, salary, project):
# data members
self.name = name #Public (accessible from outside and inside the class)
self.id = id #Public
self._project = project #Protected (accessible within the class and its subclass)
self.__salary = salary #Private (accessible only inside the class it is declared)
Copy code

Public Member

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:
# constructor
def __init__(self, name, salary):
# public data members
self.name = name
self.salary = salary
# public instance methods
def show_sal(self):
# accessing public data member
print("Name: ", self.name, 'Salary:', self.salary)
# creating object of a class
emp = Employee('James', 100000)
# accessing public data members
print("Name: ", emp.name, 'Salary:', emp.salary)
Copy code
Output:
Name:James Salary:100000

Private Member

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:
# constructor
def __init__(self, name, salary):
# public data member
self.name = name
# private member
self.__salary = salary
# creating object of a class
emp = Employee('James, 100000)
# accessing private data members
print('Salary:', emp.__salary)
Copy code

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.

Example: 


 
class Employee:
# constructor
def __init__(self, name, salary):
# public data member
self.name = name
# private member
self.__salary = salary
# public instance methods
def show_sal(self):
# private members are accessible from a class
print("Name: ", self.name, 'Salary:', self.__salary)
# creating an object of a class
emp = Employee('James', 100000)
# calling public method of the class
emp.show_sal()
Copy code
Output:
Name:James Salary:100000

Protected Member

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 class
class Company:
def __init__(self):
# Protected member
self._project = "Python"
# child class
class Employee(Company):
def __init__(self, name):
self.name = name
Company.__init__(self)
def show_sal(self):
print("Employee name :", self.name)
# Accessing protected member in child class
print("Working on project :", self._project)
c = Employee("James")
c.show_sal()
# Direct access protected data member
print('Project:', c._project)
Copy code
About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio