2.1.4 · HinglishOOP Fundamentals
Instance methods, class methods (`@classmethod`), static methods (`@staticmethod`)
2.1.4· Coding › OOP Fundamentals
Teeno types ki zaroorat hi KYU padti hai?
KIYA hai har ek
Binding KAISE actually kaam karti hai (scratch se derivation)
Hum derive karenge ki self "automatically kyun aata hai", isko memorise karne ki jagah.
Toh teeno same mechanism hain, bas "main kya inject karun" ka rule alag hai.

Worked Example 1 — Ek Circle jo teeno dikhata hai
class Circle:
PI = 3.14159 # class attribute (shared)
def __init__(self, r):
self.r = r # instance attribute (per-object)
def area(self): # INSTANCE method
return Circle.PI * self.r ** 2 # needs self.r
@classmethod
def unit(cls): # CLASS method (factory)
return cls(1) # builds an instance via cls
@staticmethod
def is_valid(r): # STATIC method (pure helper)
return r > 0c = Circle(2)
c.area() # 12.566 -> needs the object's r
Circle.unit() # Circle(r=1) -> no object needed, uses cls
Circle.is_valid(-1) # False -> no self, no clsareainstance method kyun hai? Yehself.rpar depend karta hai, jo har object mein alag hota hai.unitclassmethod kyun hai (static nahi)? Yehcls(1)return karta hai.clsuse karne ka matlab hai ki ek subclassclass Ball(Circle)meinBall.unit()→ ekBallbanegi,Circlenahi. Yahi factories ke liye@classmethodprefer karne ki killer wajah hai.is_validstatic kyun hai? Yeh na object data use karta hai na class data — yeh bas related logic hai.
Worked Example 2 — cls class name hard-code karne se kyun better hai
class Animal:
species = "generic"
@classmethod
def describe(cls):
return f"I am a {cls.species}" # cls, NOT Animal
class Dog(Animal):
species = "dog"
Animal.describe() # "I am a generic"
Dog.describe() # "I am a dog" <-- cls is Dog here- Yeh step (
cls.species) kyun? Kyunkiclswahi class hoti hai jiske through call aaya.Dogke zariye call karne parcls = Dogho jaata hai, toh yeh sahi tarah seDog.speciespadhta hai. AgarAnimal.specieslikhte, toh subclasses ignore ho jaate.
Worked Example 3 — Alternate-constructor pattern (classmethods ka 80/20 use)
class Date:
def __init__(self, y, m, d):
self.y, self.m, self.d = y, m, d
@classmethod
def from_string(cls, s): # "2024-05-01"
y, m, d = map(int, s.split("-"))
return cls(y, m, d) # Why cls? subclass-friendly factory- Yeh step kyun? Ek class mein sirf ek
__init__ho sakta hai, lekin object banane ke kai tarike ho sakte hain. Classmethods aapko multiple named constructors dete hain.
Common Mistakes (Steel-manned)
Recall Feynman: 12-saal ke bachche ko samjhao
Ek cookie cutter (class) aur usse bane cookies (instances) imagine karo.
- Instance method ek specific cookie ke baare mein poochta hai: "TU kitna bada hai?" — use woh cookie chahiye (
self). - Class method cutter ke baare mein poochta hai: "mujhe ek bilkul naya standard cookie banao" — use cutter chahiye (
cls), koi cookie nahi. - Static method ek sticky note hai jo cutter par chipka hai: ek kaam aane wala rule jaise "dough 0 cm se zyada moti honi chahiye" — ise cutter ya kisi cookie ki zaroorat nahi, bas paas mein rakha hai kyunki topic se related hai.
Flashcards
Instance method ko kaunsa automatic pehla argument milta hai?
self, woh specific instance jis par method call hua.@classmethod ko kaunsa automatic pehla argument milta hai?
cls, us class ka reference jiske zariye call hua.@staticmethod ko kaunsa automatic argument milta hai?
Kuch nahi — yeh ek plain function ki tarah behave karta hai jo class mein namespaced hai.
Factory/alternate constructors ke liye @classmethod ko @staticmethod se kyun prefer karte hain?
Kyunki
cls inheritance respect karta hai: subclass call subclass instance banata hai, parent nahi.c.area() ko equivalent explicit function call mein rewrite karo.
Circle.area(c) — object pehle positional argument ban jaata hai.Instance method ke liye def f(): nahi balki def f(self): kyun likhna padta hai?
Python object ko pehle positional arg ke roop mein pass karta hai, toh ek parameter slot hona chahiye use receive karne ke liye.
obj.method hood ke neeche kya evaluate hota hai?
type(obj).__dict__['method'].__get__(obj, type(obj)) — descriptor protocol ke zariye ek bound method.Classmethod mein ClassName.x ki jagah cls.x kyun use karte hain?
Taaki overridden
x wale subclasses apni value use karein; cls actual calling class hoti hai.Agar PI ek class attribute hai aur aap self.PI = 3.14 assign karo toh kya hota hai?
Ek naya instance attribute banta hai jo class wale ko shadow karta hai; shared class value unchanged rehti hai.
Kaunsa method type instance aur class state dono padh/modify kar sakta hai?
Instance method (iske paas
self hai, aur class type(self) se accessible hai).Connections
- OOP Fundamentals - Classes and Objects
- Instance vs Class attributes
- Inheritance and method resolution order (MRO)
- Descriptors and the __get__ protocol
- Decorators
- Factory design pattern