✨ Dunder (Magic) Methods

Last Updated: 05 Sept 2025


  • Dunder = Double Underscore
  • Special methods in Python that start and end with __.
  • Used to customize object behavior.

Hinglish Tip 🗣: Normal methods tum call karte ho.Dunder methods Python khud hi call karta hai jab tum operator ya built-in function use karte ho.


✏ Common Dunder Methods

  • __init__ (constructor) - Initialize object with values
  • __str__ - Pretty object print
  • __len__ - Length of object
  • __add__ - Operator overloading

💡 Example 1:

class Song:
    def __init__(self, title, duration):
        self.title = title
        self.duration = duration

    def __str__(self):
        return f"Song: {self.title}"

    def __len__(self):
        return self.duration

s = Song("Shape of You", 240)
print(s)        # Song: Shape of You
print(len(s))   # 240

💡 Example 2: __add__

class Money:
    def __init__(self, amount):
        self.amount = amount

    def __add__(self, other):
        return Money(self.amount + other.amount)

    def __str__(self):
        return f"₹{self.amount}"

m1 = Money(100)
m2 = Money(200)
print(m1 + m2)   # ₹300

💡 Quick Practice