Difference Between Abstraction and Encapsulation in Python | Simple Words + Examples


🔸 Let’s Understand Both:

FeatureAbstractionEncapsulation
MeaningHide how it works, show only what it doesHide data and code in one unit
FocusOn functionalityOn security and data protection
Used withAbstract Classes, @abstractmethodPrivate variables, methods, classes
Real-life ideaTV remote – You don’t know how it works insideMedicine 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 PointAbstractionEncapsulation
PurposeHides unnecessary detailsHides sensitive data
How it’s doneWith abstract classes & methodsUsing private variables & methods
Access control?NoYes (__private)
Real-life comparisonTV remoteMedicine 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.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *