Magic Methods (Dunder Methods)
Unlock Python's magic! Learn to overload operators and customize object behavior with special methods.
Unlock Python's magic! Learn to overload operators and customize object behavior with special methods. This hands-on tutorial focuses on practical implementation of magic methods (dunder methods) concepts.
Magic Methods (Dunder Methods)
Magic methods (also called dunder methods for "double underscore") are special methods that let you customize how your objects behave with Python's built-in operations.
What are Magic Methods?
Methods with names like __init__, __str__, __add__ are magic methods. They're called automatically by Python in specific situations.
Common Magic Methods (Review)
You've already seen some:
Arithmetic Operators ➕➖✖️➗
Overload arithmetic operators to work with your custom objects.
| Operator | Method | Example |
|---|---|---|
+ | add | a + b |
- | sub | a - b |
* | mul | a * b |
/ | truediv | a / b |
// | floordiv | a // b |
% | mod | a % b |
** | pow | a ** b |
Comparison Operators 🔍
Make your objects comparable.
| Operator | Method | Example |
|---|---|---|
== | eq | a == b |
!= | ne | a != b |
< | lt | a < b |
<= | le | a <= b |
> | gt | a > b |
>= | ge | a >= b |
Container Methods 📦
Make your objects behave like lists or dictionaries.
| Method | Purpose | Example |
|---|---|---|
| len | Length | len(obj) |
| getitem | Get item | obj[key] |
| setitem | Set item | obj[key] = value |
| delitem | Delete item | del obj[key] |
| contains | Membership | key in obj |
Callable Objects: __call__ 📞
Make your objects callable like functions!
Context Managers Preview: __enter__ and __exit__
These methods enable the with statement (we'll cover this more in Chapter 28).
Coding Challenge: Custom Vector Class 🎯
Create a complete Vector2D class with all operations.
AI Mentor
Confused about "Python magic methods dunder operator overloading"? Ask our AI mentor for a simplified explanation.
Quiz
Quiz
Question 1 of 5Which magic method is called for the + operator?
Key Takeaways
✅ Magic methods customize object behavior with operators.
✅ Arithmetic operators use __add__, __sub__, __mul__, etc.
✅ Comparison operators use __eq__, __lt__, __gt__, etc.
✅ Container methods enable len(), [], and in.
✅ __call__ makes objects callable like functions.
✅ __enter__/__exit__ enable context managers.
What's Next?
In the next lesson, we'll learn about Class Methods & Static Methods - different types of methods for different purposes.
Keep coding! 🚀