📘 Lesson  ·  Lesson 84

Magic Methods (Dunder)

What are Dunder Methods?

💡 At a Glance

Magic methods (or "dunder" methods) start and end with double underscores. They let your objects work with built-in operations like +, len(), print().

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

Summary

  • __init__ sets up the object; __str__ controls print(); __len__ controls len().
  • __add__ lets you use + on your objects.
← Back to Python Tutorial
🔗

Share this topic with a friend

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

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

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

💻 Live Code Editor

This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.