Abstract base classes — ABC module, `@abstractmethod`
2.1.13· Coding › OOP Fundamentals
WHAT is an ABC?
WHY do we need them?
Do bade fayde:
- Fail early, fail loud — missing methods instantiation par pakdi jaati hain, baad mein nahi.
- 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 CALLEDYeh 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 areaYeh 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 ✅ worksYeh step kyun? Jab Circle area override kar deta hai, uska __abstractmethods__ set empty ho jaata hai → instantiation allowed.

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() existsYeh 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?
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?
ABCMeta na ho.Ek subclass contract kaise satisfy karti hai?
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?
super().method() ke zariye ise reuse kar sakti hain.Kya Python ka ABC check karta hai ki overriding methods ke signatures match karte hain?
Abstract class instantiate karne par kaun sa error message aata hai?
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= 0iske analogues hain. - Metaclasses and ABCMeta — woh machinery jo
__abstractmethods__ko power deti hai. - Protocols (typing.Protocol) — nominal ABCs ka structural alternative.