Encapsulation is one of the core principles of Object-Oriented Programming (OOP).
Encapsulation means binding data (variables) and methods (functions) together inside a class and restricting direct access to some of the object’s components.
In simple words:
Encapsulation = Data Hiding + Data Protection
It helps protect data from accidental modification.
Why Encapsulation is Important
- Protects sensitive data
- Improves security
- Controls how data is accessed
- Makes code more organized
Example Without Encapsulation
class Student:
def __init__(self, name, marks):
self.name = name
self.marks = markss1 = Student("Hira", 85)
s1.marks = -50 # Invalid value
print(s1.marks)
Here, anyone can change marks to an invalid value.
Encapsulation Using Private Variables
In Python, we make variables private by adding double underscore __ before the variable name.
class Student:
def __init__(self, name, marks):
self.name = name
self.__marks = marks # Private variable def get_marks(self):
return self.__marks def set_marks(self, value):
if value >= 0:
self.__marks = value
else:
print("Invalid marks")s1 = Student("Hira", 85)print(s1.get_marks())s1.set_marks(90)
print(s1.get_marks())s1.set_marks(-10) # Invalid
Output
85
90
Invalid marks
Now:
__markscannot be accessed directly- It must be accessed using methods
- Validation is possible
Accessing Private Variable Directly (Not Recommended)
print(s1._Student__marks)
This works because Python uses name mangling, but it should not be used in practice.
Access Specifiers in Python
Python does not have strict access modifiers like other languages, but it follows naming conventions:
Public Variableself.name
Can be accessed anywhere
Protected Variableself._name
Should not be accessed outside class (convention only)
Private Variableself.__name
Cannot be accessed directly
Benefits of Encapsulation
- Better control over data
- Prevents accidental changes
- Improves code maintainability
- Makes debugging easier
Key Takeaway
Encapsulation protects object data by restricting direct access and allowing controlled access through methods.
It ensures safe, secure, and structured programming in OOP.