OOP Basics
__init__ Constructor
Object Setup
💡 __init__ ek move-in checklist hai jo har naye ghar (object) ke liye automatically chalti hai — zaroori setup (furniture placement) automatically ho jaata hai object banate hi.
__init__ Python ka constructor hai — object banate waqt automatically call hota hai. "Dunder" (double underscore) naming Python ki convention hai special/magic methods ke liye — __init__, __str__, waghera, aage dunder-methods topic mein detail se.
Default parameter values C++/Java jaise hi hain — __init__ mein bhi use kar sakte ho, taaki object banate waqt kuch values optional ho sakein.
class Student:
def __init__(self, name, age=18): # age ka default value
self.name = name
self.age = age
s1 = Student("Aarav") # age default 18 use hoga
s2 = Student("Riya", 20) # explicit age
print(s1.age) # 18
print(s2.age) # 20🏗️
__init__ ek move-in checklist hai jo har naye ghar (object) ke liye automatically chalti hai — zaroori setup (furniture placement) automatically ho jaata hai object banate hi.
1 / 2
⚡ Quick Recap
- __init__ = constructor, object banate hi automatically chalta hai
- "Dunder" methods = double underscore special methods
- Python mein constructor overloading nahi hai — sirf ek __init__
Is page mein (1 subtopics)
@classmethod decorator se "factory methods" bana sakte ho — alternative ways object banane ke, jaise ek string se parse karke object banana. Python multiple __init__ allow nahi karta, isliye classmethods ye gap fill karte hain.
class Date:
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
@classmethod
def from_string(cls, date_string): # alternative constructor
year, month, day = map(int, date_string.split("-"))
return cls(year, month, day) # cls = Date class
d1 = Date(2026, 7, 28)
d2 = Date.from_string("2026-07-28") # naya tareeka object banane ka
print(d2.year) # 2026Tip: cls parameter (self ki jagah) classmethod ko batata hai "current class kaunsi hai" — jaise self current object hai, cls current class hai.