What are Magic Methods (Dunder Methods)?
In Python, Magic Methods (also known as Dunder Methods — short for "Double Under") are special methods that start and end with double underscores, such as
__init__. They allow you to define how your objects behave with built-in Python features like operators (+, -), printing, and iteration.python
String Representations: __str__ vs __repr__
| Method | Audience | Purpose |
|---|---|---|
| str | End-User | Readable information (used by print()). |
| repr | Developer | Unambiguous description for debugging. |
python
Comparisons: __eq__, __lt__, and __gt__
By default, objects are compared based on their identity (memory address). To compare objects based on their data, you must implement these methods.
python
Operators: __add__, __sub__, and __mul__
You can define how your objects behave when used with mathematical operators. This is called Operator Overloading.
python
Containers: __len__, __getitem__, and __iter__
Want to make your object behave like a list or dictionary?
python
The Callable Magic Method: __call__
This allows you to treat an object like a function!
python
Summary
| Dunder Method | Triggered by... |
|---|---|
| init | Class() (Instantiation) |
| str | str(obj) or print(obj) |
| repr | repr(obj) (Debugging) |
| len | len(obj) |
| getitem | obj[key] |
| iter | for x in obj: |
| eq | obj1 == obj2 |
| add | obj1 + obj2 |
| call | obj() |
| Best For | Clean syntax, operator overloading, list-like objects |
| bool | if obj: |
| contains | x in obj |
| enter / exit | with obj: (Context Manager) |