📘 Lesson · Lesson 84
Magic Methods (Dunder)
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.
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 करने देता है।