📦 Encapsulation in Python
Wrapping Data and Methods Together
🔹 DefinitionEncapsulation in Python is an object-oriented programming concept that means wrapping data (variables) and methods (functions) together into a single unit, called a class.
In simple human language, encapsulation is about protecting data and controlling how it is accessed or modified. Instead of allowing direct access to variables, encapsulation encourages using methods to interact with data. This helps prevent accidental changes and keeps the program safe and well-organized.
Encapsulation is closely related to data hiding, which improves security and reliability of the code.
📌 Basic Syntax of Encapsulation
class ClassName:
def __init__(self):
self.variable = value
def method(self):
pass
Encapsulation is mainly achieved using access specifiers and getter/setter methods.
📂 Types of Encapsulation in Python
In Python, encapsulation is commonly understood through three levels, based on access control.
1️⃣ Public Encapsulation
DefinitionPublic encapsulation means class members are freely accessible from anywhere.
Example
class Student:
def __init__(self):
self.name = "Rahul"
obj = Student()
print(obj.name)
Here, name is public. Anyone can read or modify it directly. This type is used when data does not need protection.
2️⃣ Protected Encapsulation
DefinitionProtected encapsulation allows access within the class and its child classes.
Example
class Student:
def __init__(self):
self._age = 20
class Child(Student):
def show(self):
print(self._age)
obj = Child()
obj.show()
The single underscore indicates that the variable should be treated as protected. It is a warning to developers to use it carefully.
3️⃣ Private Encapsulation
DefinitionPrivate encapsulation restricts access only to the same class.
Example
class Student:
def __init__(self):
self.__marks = 90
def get_marks(self):
return self.__marks
obj = Student()
print(obj.get_marks())
The double underscore hides the variable using name mangling. Direct access is blocked, and data can only be accessed through methods, ensuring strong data protection.
🔑 Key Points to Remember
- Encapsulation binds data and methods together
- Helps protect data from accidental changes
- Uses public, protected, and private members
- Improves security and code maintainability
📌 Conclusion
Encapsulation improves data security, code clarity, and maintainability. By controlling access to data, Python programs become safer and easier to manage. It is one of the core pillars of object-oriented programming.