📘 Lesson  ·  Lesson 84

Magic Methods (Dunder)

Dunder Methods क्या हैं?

💡 एक नज़र में

Magic methods (या "dunder") double underscores से शुरू और खत्म होती हैं। ये आपके objects को +, len(), print() जैसी built-in operations के साथ काम करने देती हैं।

Example

Python
class Book:
    def __init__(self, pages):
        self.pages = pages
    def __str__(self):
        return f"Book with {self.pages} pages"
    def __len__(self):
        return self.pages
    def __add__(self, other):
        return Book(self.pages + other.pages)

b1 = Book(100)
b2 = Book(50)
print(b1)              # __str__
print(len(b1))         # __len__
print((b1 + b2).pages) # __add__
Book with 100 pages 100 150

सारांश

  • __init__ object setup करता; __str__ print() control; __len__ len() control करता है।
  • __add__ आपके objects पर + use करने देता है।
← Back to Python Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 लाइव कोड एडिटर

इस पेज के प्रोग्राम यहीं तैयार हैं — चलाएँ, बदलें और सीखें। कुछ भी इंस्टॉल किए बिना।
OneCompiler द्वारा संचालित। कोड एडिटर में अपने आप आ जाता है — Run दबाकर आउटपुट देखें। अगर एडिटर न खुले तो नए टैब में खोलें.