🧙♂️ What Are Magic Methods in Python?
🔹 Also called:
- Dunder methods (because they start and end with double underscores:
__method__
)
- Special methods
🔹 Purpose:
They allow you to customize the behavior of your objects for:
- Operators (
+
, >
, ==
)
- Built-in functions (
len()
, str()
, repr()
)
- Type conversion (
int()
, float()
)
- Context managers (
with
)
- Iteration (
for
)
- and more...
🧠 Real-Life Analogy
Imagine you're designing your own robot.
You want it to behave specially when:
- ✅ You print it →
__str__
- ✅ You compare it to another →
__eq__
, __lt__
- ✅ You add it to something →
__add__