Python

Magic Methods (Dunder Methods)

Unlock Python's magic! Learn to overload operators and customize object behavior with special methods.

By TechCoder TeamLast updated: 2026-06-02
In a Nutshell

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:

PYTHON PLAYGROUND
⏳ Loading editor…

Arithmetic Operators ➕➖✖️➗

Overload arithmetic operators to work with your custom objects.

OperatorMethodExample
+adda + b
-suba - b
*mula * b
/truediva / b
//floordiva // b
%moda % b
**powa ** b
PYTHON PLAYGROUND
⏳ Loading editor…

Comparison Operators 🔍

Make your objects comparable.

OperatorMethodExample
==eqa == b
!=nea != b
<lta < b
<=lea <= b
>gta > b
>=gea >= b
PYTHON PLAYGROUND
⏳ Loading editor…

Container Methods 📦

Make your objects behave like lists or dictionaries.

MethodPurposeExample
lenLengthlen(obj)
getitemGet itemobj[key]
setitemSet itemobj[key] = value
delitemDelete itemdel obj[key]
containsMembershipkey in obj
PYTHON PLAYGROUND
⏳ Loading editor…

Callable Objects: __call__ 📞

Make your objects callable like functions!

PYTHON PLAYGROUND
⏳ Loading editor…

Context Managers Preview: __enter__ and __exit__

These methods enable the with statement (we'll cover this more in Chapter 28).

PYTHON PLAYGROUND
⏳ Loading editor…

Coding Challenge: Custom Vector Class 🎯

Create a complete Vector2D class with all operations.

PYTHON PLAYGROUND
⏳ Loading editor…

AI Mentor

Confused about "Python magic methods dunder operator overloading"? Ask our AI mentor for a simplified explanation.

Quiz

Quiz

Question 1 of 5

Which magic method is called for the + operator?

__plus__
__add__
__sum__
__combine__

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! 🚀