OOP Basics

Dunder (Magic) Methods

__str__, __len__, __eq__
💡 Dunder methods Python ke "hooks" hain — jaise ek universal remote ke buttons, jinhe tum apni class ke liye customize kar sakte ho. print(obj) ka behavior chahiye customize karna? __str__ implement karo. len(obj) chahiye kaam kare? __len__ implement karo.

Dunder ("double underscore") methods Python ke built-in operators/functions (print, len, ==, +) ko apni custom classes ke saath kaam karne dete hain — C++ ke operator overloading jaisa concept, lekin Python mein ye poori language mein consistently use hota hai.

Common dunder methods: __str__ (print() ke liye readable string), __len__ (len() function), __eq__ (== comparison), __add__ (+ operator), __repr__ (developer-friendly representation, debugging ke liye).

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __str__(self):              # print(p) ke liye
        return f"Point({self.x}, {self.y})"

    def __eq__(self, other):        # == operator ke liye
        return self.x == other.x and self.y == other.y

    def __add__(self, other):       # + operator ke liye
        return Point(self.x + other.x, self.y + other.y)

p1 = Point(1, 2)
p2 = Point(3, 4)

print(p1)              # "Point(1, 2)" — __str__ automatically use hota hai
print(p1 == Point(1, 2))  # True — __eq__ use hota hai
print(p1 + p2)          # "Point(4, 6)" — __add__ use hota hai
Dunder methods Python ke "hooks" hain — jaise ek universal remote ke buttons, jinhe tum apni class ke liye customize kar sakte ho. print(obj) ka behavior chahiye customize karna? __str__ implement karo. len(obj) chahiye kaam kare? __len__ implement karo.
1 / 2
⚡ झट से Recap
  • Dunder methods = Python ke built-in operators/functions ke "hooks"
  • __str__ (print), __len__ (len()), __eq__ (==), __add__ (+)
  • C++ ke operator overloading jaisa, lekin poore language mein consistent
इस page में (1 subtopics)

__len__ apni class ko len() ke saath compatible banata hai. __getitem__ [] indexing enable karta hai — dono milkar apni class ko list-jaisi behavior de sakte hain.

class Playlist:
    def __init__(self, songs):
        self.songs = songs

    def __len__(self):
        return len(self.songs)

    def __getitem__(self, index):
        return self.songs[index]

p = Playlist(["Song A", "Song B", "Song C"])
print(len(p))     # 3 — __len__ use hota hai
print(p[1])         # "Song B" — __getitem__ use hota hai

for song in p:      # __getitem__ hone se, ye bhi automatically kaam karta hai!
    print(song)
💡Tip: __getitem__ implement karne se, class automatically iterable ban jaati hai (for loop mein use ho sakti hai) — Python internally __getitem__(0), __getitem__(1)... try karta hai jab tak IndexError na aaye.