- Learning Objectives
- Prerequisites
- Introduction
- What is Encapsulation?
- Why is Encapsulation Required?
- Real-World Example
- Data and Methods
- Data Hiding
- Encapsulation vs Data Hiding
- Achieving Encapsulation in Python
- Getters and Setters
- Python Properties
- Internal Working
- Summary
After completing this chapter, you will be able to:
- Understand Encapsulation.
- Explain the need for Encapsulation.
- Differentiate Encapsulation and Data Hiding.
- Create encapsulated classes.
- Use Getters and Setters.
- Use Python Properties.
- Apply Encapsulation in real-world applications.
Before learning this chapter, you should know:
- Classes
- Objects
- Instance Variables
- Methods
- self Keyword
Object-Oriented Programming is built on four fundamental pillars.
They are:
- Encapsulation
- Abstraction
- Inheritance
- Polymorphism
The first pillar is Encapsulation.
Encapsulation helps us organize data and methods into a single unit while controlling how the data is accessed and modified.
It improves security, maintainability, and code organization.
Encapsulation is the process of combining data (variables) and methods (functions) into a single unit called a class.
The methods provide a controlled way to access and modify the data.
Wrapping data and methods together inside a class is called Encapsulation.
Suppose we are developing a Banking Application.
Every customer has:
- Account Number
- Account Holder Name
- Balance
- ATM PIN
Should every user be able to modify the balance directly?
No.
Instead,
the balance should only be modified using methods such as:
- Deposit()
- Withdraw()
This prevents accidental or unauthorized modifications.
Encapsulation provides this controlled access.
Consider an ATM Machine.
You can:
- Deposit Money
- Withdraw Money
- Check Balance
But you cannot directly access or change the bank's internal database.
The ATM provides controlled access through specific operations.
Similarly,
a class provides controlled access to its data using methods.
Encapsulation consists of two components.
Stores the state of an object.
Example
Name
Age
Salary
Balance
Perform operations on the data.
Example
Deposit()
Withdraw()
Display()
Update()
+--------------------------------+
Student Class
----------------------------------
Data
• Name
• Age
• Marks
----------------------------------
Methods
• display()
• updateMarks()
----------------------------------
+--------------------------------+
Data Hiding means restricting direct access to sensitive data.
Instead of accessing variables directly,
users interact with the object through methods.
Example
Balance
↓
Deposit()
Withdraw()
No.
Many beginners think both terms are the same, but they are different.
- Wraps data and methods into one unit.
- Focuses on organization and controlled access.
- Restricts direct access to data.
- Focuses on protecting sensitive information.
Data Hiding is one benefit of Encapsulation, but they are not identical concepts.
| Encapsulation | Data Hiding |
|---|---|
| Combines data and methods into a class | Restricts direct access to data |
| Focuses on code organization | Focuses on security |
| Achieved using classes | Achieved using access control and naming conventions |
| Improves maintainability | Protects sensitive information |
Encapsulation is achieved by:
- Creating a class.
- Defining instance variables.
- Providing methods to access or modify the data.
- Using public, protected, or private members where appropriate.
Instead of accessing variables directly,
we use methods.
A Getter method returns the value of a variable.
Example
def get_name(self):
return self.__nameA Setter method updates the value of a variable.
Example
def set_name(self, name):
self.__name = namePython provides the @property decorator to create getter methods in a more Pythonic way.
Example
@property
def name(self):
return self.__nameA setter can also be created using:
@name.setterProperties allow controlled access while keeping the syntax simple for users of the class.
User
↓
Calls Method
↓
Method Validates Data
↓
Updates Variable
↓
Returns Result
Instead of modifying variables directly,
methods control the entire process.
- Improves security.
- Protects sensitive data.
- Makes code reusable.
- Improves maintainability.
- Supports modular programming.
- Reduces coupling between components.
- Slightly increases code size.
- Requires additional methods for data access.
- May add complexity for very small programs.
Encapsulation is used in:
- Banking Systems
- Hospital Management Systems
- ATM Software
- Student Management Systems
- Employee Payroll Systems
- E-Commerce Applications
- Inventory Management Systems
In this part, we learned:
- Encapsulation
- Need for Encapsulation
- Data Hiding
- Components of Encapsulation
- Getters
- Setters
- Python Properties
- Internal Working
- Advantages
- Real-Time Applications
Write a Python program to demonstrate Encapsulation.
class Student:
def __init__(self):
self.name = "Rahul"
self.age = 21
def display(self):
print("Name :", self.name)
print("Age :", self.age)
student = Student()
student.display()Name : Rahul
Age : 21
In this program,
- The data (
nameandage) and - The method (
display())
are combined inside a single class.
This is Encapsulation.
Write a Python program to demonstrate Encapsulation using private variables.
class BankAccount:
def __init__(self):
self.__balance = 10000
def display_balance(self):
print("Balance :", self.__balance)
account = BankAccount()
account.display_balance()Balance : 10000
The variable
__balanceis private.
It cannot be accessed directly from outside the class.
The balance is accessed through the method
display_balance()This provides controlled access to the data.
Write a Python program to retrieve a private variable using a Getter method.
class Student:
def __init__(self):
self.__name = "Rahul"
def get_name(self):
return self.__name
student = Student()
print(student.get_name())Rahul
The Getter method returns the value of the private variable without allowing direct access.
Write a Python program to update a private variable using a Setter method.
class Student:
def __init__(self):
self.__name = ""
def set_name(self, name):
self.__name = name
def get_name(self):
return self.__name
student = Student()
student.set_name("Priya")
print(student.get_name())Priya
Instead of modifying the variable directly,
the Setter method updates the value.
This allows validation before assigning new values.
Write a Python program to validate student age before storing it.
class Student:
def __init__(self):
self.__age = 0
def set_age(self, age):
if age >= 18:
self.__age = age
else:
print("Invalid Age")
def get_age(self):
return self.__age
student = Student()
student.set_age(21)
print(student.get_age())21
Before storing the value,
the Setter validates the input.
Invalid values are rejected.
This is one of the biggest advantages of Encapsulation.
Write a Python program using the @property decorator.
class Student:
def __init__(self):
self.__name = "Rahul"
@property
def name(self):
return self.__name
student = Student()
print(student.name)Rahul
The @property decorator allows us to access a method like an attribute.
Instead of writing
student.get_name()we simply write
student.nameThis is the recommended Pythonic approach.
class Student:
def __init__(self):
self.__marks = 0
@property
def marks(self):
return self.__marks
@marks.setter
def marks(self, value):
if value >= 0:
self.__marks = value
student = Student()
student.marks = 95
print(student.marks)95
The setter validates the data before storing it.
The user interacts with the object as if marks were a normal attribute, while the validation logic remains hidden.
User
↓
Setter Method
↓
Validation
↓
Private Variable Updated
↓
Getter Method
↓
Value Returned
Student Object
│
▼
+------------------------------+
__name
↓
Rahul
------------------------------
get_name()
set_name()
display()
+------------------------------+
- Protects sensitive data.
- Prevents unauthorized modification.
- Improves maintainability.
- Supports validation.
- Promotes code reuse.
- Makes programs modular.
- Use private variables for sensitive data.
- Validate input inside Setter methods.
- Prefer
@propertyfor cleaner code. - Avoid exposing private data directly.
- Keep Getter and Setter methods simple.
Accessing private variables directly.
❌ Incorrect
student.__nameProduces
AttributeError
Not validating data.
self.__age = ageAlways validate user input before storing it.
Making every variable private unnecessarily.
Not every variable needs to be private.
Use private members only for sensitive or controlled data.
Encapsulation is widely used in:
- Banking Systems
- ATM Applications
- Hospital Management Systems
- Payroll Systems
- Student Management Systems
- E-Commerce Applications
- Library Management Systems
Encapsulation is the process of combining data and methods into a single unit called a class.
Encapsulation protects data, improves security, and provides controlled access through methods.
Data Hiding is the process of restricting direct access to sensitive data.
It is one of the benefits of Encapsulation.
Encapsulation combines data and methods into a class.
Data Hiding restricts direct access to data.
A Getter method returns the value of a private variable.
A Setter method updates the value of a private variable, often after validating the input.
It provides controlled access to data while allowing attributes to be accessed using simple dot notation.
- Create an Employee class with private salary and Getter/Setter methods.
- Create a BankAccount class that validates withdrawals.
- Create a Product class using
@property. - Create a Student class that validates marks.
- Create a Customer class with private mobile number and update it using a Setter.
- Encapsulation combines data and methods into one unit.
- Data Hiding protects sensitive data.
- Private variables use
__. - Getter methods retrieve values.
- Setter methods update values.
@propertyis the Pythonic way to implement controlled access.- Validation should be performed inside Setter methods.
In this chapter, you learned:
- Encapsulation
- Data Hiding
- Encapsulation vs Data Hiding
- Getters
- Setters
- Python Properties
- Internal Working
- Practical Programs
- Best Practices
- Common Mistakes
- Interview Questions
- Practice Programs
- Quick Revision