2.1.13 · HinglishOOP Fundamentals

Abstract base classes — ABC module, `@abstractmethod`

1,834 words8 min readRead in English

2.1.13 · Coding › OOP Fundamentals


WHAT is an ABC?


WHY do we need them?

Do bade fayde:

  1. Fail early, fail loud — missing methods instantiation par pakdi jaati hain, baad mein nahi.
  2. Self-documenting design — ABC exactly list karta hai ki ek subclass tumhe kya dene wali hai.

HOW it works (derivation from first principles)

Hume magic memorise karne ki zaroorat nahi — hum behaviour ko build up kar sakte hain.

Step 1 — Ek plain base class kuch bhi enforce NAHI karti.

class Shape:
    def area(self):
        raise NotImplementedError   # only fails when CALLED

Yeh step kyun? Yeh "poor man's ABC" hai. Error tabhi fire hoti hai jab koi actually area() call kare. Tum phir bhi Shape() create kar ke pass kar sakte ho — bomb chupi hui hai.

Step 2 — ABC se inherit karo + method ko abstract mark karo.

from abc import ABC, abstractmethod
 
class Shape(ABC):
    @abstractmethod
    def area(self):
        ...

Yeh step kyun? ABC ek special metaclass (ABCMeta) use karta hai. Jab tum Shape() try karte ho, metaclass __abstractmethods__ naam ki ek internal set check karta hai. Agar woh non-empty hai, instantiation turant block ho jaati hai.

Step 3 — Enforcement dekho.

Shape()        # TypeError: Can't instantiate abstract class Shape
               # with abstract method area

Yeh step kyun? Error ab construction time par hoti hai aur missing method ka naam bataati hai. Yahi toh poora point hai.

Step 4 — Ek concrete subclass contract clear karti hai.

class Circle(Shape):
    def __init__(self, r):
        self.r = r
    def area(self):
        return 3.14159 * self.r ** 2
 
Circle(2).area()   # 12.566  ✅ works

Yeh step kyun? Jab Circle area override kar deta hai, uska __abstractmethods__ set empty ho jaata hai → instantiation allowed.

Figure — Abstract base classes — ABC module, `@abstractmethod`

The mechanism in one sentence

__abstractmethods__ ek frozenset hai jo ABCMeta dwara automatically compute hoti hai har baar jab ek class define hoti hai. Inherited-lekin-unimplemented abstract methods set mein rehti hain; override ki gayi hatayi jaati hain.


Going deeper: combining decorators


Worked example: a payment system

from abc import ABC, abstractmethod
 
class PaymentProcessor(ABC):
    @abstractmethod
    def pay(self, amount): ...
    @abstractmethod
    def refund(self, amount): ...
 
class CardProcessor(PaymentProcessor):
    def pay(self, amount):    return f"Charged {amount} to card"
    def refund(self, amount): return f"Refunded {amount} to card"

Do abstract methods kyun? Contract kehta hai "kisi bhi processor ko pay AUR refund dono karne chahiye." Agar CardProcessor sirf pay define kare, toh __abstractmethods__ mein abhi bhi refund hoga, isliye CardProcessor(...) TypeError raise karega. Step-by-step kyun: metaclass implemented names ko inherited abstract set se subtract karta hai; refund bachta hai → set non-empty → blocked.

def checkout(p: PaymentProcessor, amt):
    return p.pay(amt)      # safe: ANY subclass guarantees pay() exists

Yeh safe kyun hai: type hint + ABC contract ka matlab hai ki checkout tak pahunchne wala har object provably pay rakhta hai. Koi defensive hasattr ki zaroorat nahi.


Common mistakes (Steel-man each)


Recall Feynman: explain to a 12-year-old

Socho ek fill-in-the-blanks worksheet jo ek toy banane ke liye hai. Worksheet kehti hai: "Har robot mein walk() button AUR talk() button hona CHAHIYE." Yeh koi complete robot nahi hai — tum worksheet se khel nahi sakte. Jo bhi real robot banana chahta hai use DONO buttons fill in karne honge. Agar woh talk() button bhool jaaye, toh factory unka robot banana refuse kar deti hai aur exactly batati hai kaunsa button missing hai — factory chhodni se pehle, nahi ki koi bachcha press kare aur kuch na ho. Worksheet = abstract base class. "MUST have" buttons = @abstractmethod. Factory check = __abstractmethods__ empty hona chahiye.


Forecast-then-Verify


Flashcards

Python mein ek class ko abstract banane ke liye kaun se do ingredients chahiye?
ABC se inherit karo (ya metaclass=ABCMeta) AUR ≥1 method ko @abstractmethod se decorate karo.
Abstract class instantiate karna kab fail hota hai?
Construction time par (TypeError), usi waqt jab tum ClassName() call karte ho, nahi ki baad mein koi method call hone par.
Kaunsa attribute determine karta hai ki class instantiate ho sakti hai ya nahi?
__abstractmethods__ — ek frozenset; instantiation tab allowed jab yeh empty ho.
Kya @abstractmethod akela (ABC inherit kiye bina) kuch bhi enforce karta hai?
Nahi — yeh silently ignore hota hai jab tak metaclass ABCMeta na ho.
Ek subclass contract kaise satisfy karti hai?
Har abstract method ko apni body mein override (redefine) karke.
Abstract property ke liye sahi decorator order?
@property upar, @abstractmethod directly def ke upar (abstractmethod innermost).
Kya ek abstract method mein real code ho sakta hai?
Haan — subclasses ko phir bhi override karna padega lekin super().method() ke zariye ise reuse kar sakti hain.
Kya Python ka ABC check karta hai ki overriding methods ke signatures match karte hain?
Nahi — yeh sirf check karta hai ki method ka naam override hua; signatures enforce nahi hote.
Abstract class instantiate karne par kaun sa error message aata hai?
"Can't instantiate abstract class X with abstract method(s) ..." missing waalon ke naam ke saath.

Connections

  • Inheritance and Method Overriding — ABCs contract clear karne ke liye overriding par rely karti hain.
  • Polymorphism — ABCs ek common interface guarantee karte hain taaki polymorphic calls safe hon.
  • Duck Typing vs Nominal Typing — ABCs duck typing ke upar nominal (declared) typing add karte hain.
  • Interfaces in other languages — Java interface / C++ pure virtual = 0 iske analogues hain.
  • Metaclasses and ABCMeta — woh machinery jo __abstractmethods__ ko power deti hai.
  • Protocols (typing.Protocol) — nominal ABCs ka structural alternative.

Concept Map

provides

provides

uses

marks methods in

checks

non-empty blocks

resolved by overriding

fulfills

gives

weaker alternative to

Abstract Base Class

abc module

abstractmethod decorator

ABCMeta metaclass

__abstractmethods__ set

Cannot instantiate

Concrete subclass

Enforced contract

Fail early at creation

NotImplementedError base