🔸 Let’s Understand Both:
Feature | Abstraction | Encapsulation |
---|---|---|
Meaning | Hide how it works, show only what it does | Hide data and code in one unit |
Focus | On functionality | On security and data protection |
Used with | Abstract Classes, @abstractmethod | Private variables, methods, classes |
Real-life idea | TV remote – You don’t know how it works inside | Medicine capsule – It hides the inner parts |
🔹 Example of Abstraction:
from abc import ABC, abstractmethod
class Payment(ABC):
@abstractmethod
def pay(self):
pass
class UPI(Payment):
def pay(self):
print("Payment using UPI")
p = UPI()
p.pay()
✅ The user only knows they are using UPI. How it works inside is hidden.
🔹 Example of Encapsulation:
class Student:
def __init__(self):
self.__marks = 0 # private variable
def set_marks(self, m):
self.__marks = m
def get_marks(self):
return self.__marks
s = Student()
s.set_marks(95)
print(s.get_marks()) # Output: 95
✅ The marks are protected. We use methods to access them.
🧾 Summary Table
Key Point | Abstraction | Encapsulation |
---|---|---|
Purpose | Hides unnecessary details | Hides sensitive data |
How it’s done | With abstract classes & methods | Using private variables & methods |
Access control? | No | Yes (__private ) |
Real-life comparison | TV remote | Medicine capsule |
🧠 Easy Tip to Remember
- 🔍 Abstraction = “Don’t show how it works” (Focus on What)
- 🔒 Encapsulation = “Don’t let others touch my data” (Focus on How safe)
🎯 Recap in 2 Lines:
- Abstraction hides logic
- Encapsulation hides data
Both help you write clean and secure code.
Leave a Reply