📘 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.
💻 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.