2.1.4 · HinglishOOP Fundamentals

Instance methods, class methods (`@classmethod`), static methods (`@staticmethod`)

1,764 words8 min readRead in English

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.

Figure — Instance methods, class methods (`@classmethod`), static methods (`@staticmethod`)

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 > 0
c = 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 cls
  • area instance method kyun hai? Yeh self.r par depend karta hai, jo har object mein alag hota hai.
  • unit classmethod kyun hai (static nahi)? Yeh cls(1) return karta hai. cls use karne ka matlab hai ki ek subclass class Ball(Circle) mein Ball.unit() → ek Ball banegi, Circle nahi. Yahi factories ke liye @classmethod prefer karne ki killer wajah hai.
  • is_valid static 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? Kyunki cls wahi class hoti hai jiske through call aaya. Dog ke zariye call karne par cls = Dog ho jaata hai, toh yeh sahi tarah se Dog.species padhta hai. Agar Animal.species likhte, 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

Concept Map

is stored as

implements

attribute access triggers

injects self=a

injects cls=type a

injects nothing

reads/writes

can also access

reads/writes

can build

is just

this object

the class

none

Method inside class

Plain function in __dict__

__get__ descriptor protocol

Binding decision

Instance method

Class method @classmethod

Static method @staticmethod

Instance state

Class state

New instances

Namespaced utility logic

Context needed