B.Tech Students: Apply for Live Programming Internship C, C++, Java, Python ,Web page Designing, PHP Python Abstraction in OOP | LiveCodeProgramming

Abstraction in Python (OOP)

Abstraction is a key concept in OOP that hides internal details and shows only necessary features. Python provides abstraction using the abc module.

Abstraction OOP का एक महत्वपूर्ण भाग है, जो unnecessary details को छुपाकर सिर्फ जरूरी जानकारी दिखाता है। Python में हम abstraction abc module से करते हैं।

Why Use Abstraction?

  • To hide complexity from the user
  • To focus only on essential operations
  • To enforce implementation in subclasses
  • Complexity को छुपाने के लिए
  • सिर्फ important operations पर ध्यान देने के लिए
  • Subclasses में implementation को force करने के लिए

How to Implement Abstraction in Python?

Use abc.ABC as base class and @abstractmethod to declare methods that must be defined in child class.

हम abc.ABC को base class बनाते हैं और @abstractmethod से method declare करते हैं जिसे subclass में implement करना होता है।

Example 1: Abstract Employee Class
from abc import ABC, abstractmethod

class Employee(ABC):
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary

    @abstractmethod
    def calculate_bonus(self):
        pass

Output: No output — this is just an abstract base class.

We can't create object of Employee class until all abstract methods are implemented.

हम Employee class का object तभी बना सकते हैं जब उसकी सभी abstract methods implement हों।

Example 2: Implementing Subclass
class Developer(Employee):
    def calculate_bonus(self):
        return self.salary * 0.10

dev = Developer("Aryan", 50000)
print(f"Bonus for {dev.name}: ₹{dev.calculate_bonus()}")

Output:

Bonus for Aryan: ₹5000.0

Here calculate_bonus is defined in subclass, so object creation works fine.

यहाँ calculate_bonus subclass में define किया गया है, इसलिए object बन सकता है।

Example 3: Multiple Employee Types
class Manager(Employee):
    def calculate_bonus(self):
        return self.salary * 0.15

employees = [
    Developer("Ravi", 60000),
    Manager("Shruti", 80000)
]

for emp in employees:
    print(f"{emp.name} Bonus: ₹{emp.calculate_bonus()}")

Output:

Ravi Bonus: ₹6000.0
Shruti Bonus: ₹12000.0

Abstraction helps to design reusable structure for different employee types.

Abstraction से हम एक reusable structure बना सकते हैं जो हर employee type के लिए अलग bonus logic दे सकता है।