Magic Methods
Magic methods (also called dunder methods) are special methods with double underscores at the beginning and end (e.g., `__init__`, `__str__`). They allow you to define how objects behave with built‑in operations like printing, adding, comparing, and more.
Common Magic Methods
- `__init__(self, ...)` – constructor
- `__str__(self)` – informal string representation (for users)
- `__repr__(self)` – official string representation (for developers)
- `__len__(self)` – used by `len()`
- `__add__(self, other)` – addition `+`
- `__eq__(self, other)` – equality `==`
- `__lt__(self, other)` – less than `<`
- `__getitem__(self, key)` – indexing `[]`
- `__call__(self, ...)` – allows object to be called like a function
class Book:
def __init__(self, title, author):
self.title = title
self.author = author
def __str__(self):
return f"{self.title} by {self.author}"
def __len__(self):
return len(self.title) + len(self.author)
book = Book("1984", "Orwell")
print(book) # 1984 by Orwell
print(len(book)) # 11
Magic methods enable your classes to behave like built‑in types and integrate seamlessly with Python's syntax.
Two Minute Drill
- Magic methods define how objects respond to built‑in operations.
- Examples: `__str__`, `__repr__`, `__len__`, `__add__`, `__eq__`, `__getitem__`.
- Implement `__str__` for user‑friendly output, `__repr__` for debugging.
- They make custom classes feel like native Python types.
Need more clarification?
Drop us an email at career@quipoinfotech.com
