Python magic methods, also known as special methods or dunder methods, are methods with names surrounded by double underscores, such as
__init__,
__str__,
__len__,
and
__add__.
Python calls these methods automatically in response to operations performed on objects.
Instead of calling these methods directly in everyday code, you normally use ordinary Python syntax such as
print(),
len(),
arithmetic operators, comparisons, iteration, indexing, or the
with
statement. Python then looks for the appropriate special method on the object.
Understanding magic methods is important when building custom classes because they allow your objects to behave naturally like Python's built-in types. They are also common interview topics and appear frequently in frameworks and libraries.
What You Will Learn
- What magic or dunder methods are
- How __init__, __str__, and __repr__ work
- How objects customize len(), bool(), indexing, and iteration
- How comparison and arithmetic operators use special methods
- How __call__ makes objects callable
- How context managers use __enter__ and __exit__
- How __new__ differs from __init__
- How to use special methods without making classes confusing
What Are Magic Methods?
Magic methods are methods that use the naming pattern
__name__.
The term "magic" is informal. Python's documentation commonly refers to them as special methods.
They define how objects interact with Python language features. For example:
| Python Operation | Common Special Method |
|---|---|
| Object creation | __new__, __init__ |
str(obj) |
__str__ |
repr(obj) |
__repr__ |
len(obj) |
__len__ |
bool(obj) |
__bool__ |
obj[key] |
__getitem__ |
for item in obj |
__iter__, __next__ |
a + b |
__add__ |
a == b |
__eq__ |
obj() |
__call__ |
with obj |
__enter__, __exit__ |
__init__: Initializing Objects
The
__init__
method initializes a newly created object. It is one of the most commonly used special methods in Python classes.
class User:
def __init__(self, name: str, age: int):
self.name = name
self.age = age
user = User("Alex", 25)
print(user.name)
print(user.age)
When
User("Alex", 25)
is evaluated, Python creates an object and then calls
__init__()
to initialize it.
It is important to understand that
__init__()
initializes an existing object. It does not create the object itself. Object creation is associated with
__new__().
__str__: User-Friendly Representation
The
__str__
method controls the human-readable string representation used by
str()
and commonly by
print().
class User:
def __init__(self, name: str, role: str):
self.name = name
self.role = role
def __str__(self):
return f"{self.name} ({self.role})"
user = User("Alex", "Developer")
print(user)
print(str(user))
A useful
__str__
implementation should produce a readable description rather than a difficult-to-understand internal representation.
__repr__: Developer-Focused Representation
The
__repr__
method provides the object's representation intended to be useful for developers, debugging, and interactive environments.
class User:
def __init__(self, name: str, role: str):
self.name = name
self.role = role
def __repr__(self):
return (
f"User(name={self.name!r}, "
f"role={self.role!r})"
)
user = User("Alex", "Developer")
print(repr(user))
A useful
__repr__
often includes enough information to understand the object's state during debugging.
__str__ vs __repr__
| Method | Purpose |
|---|---|
__str__ |
Readable representation for users or normal output. |
__repr__ |
Useful representation for developers and debugging. |
If a class defines
__repr__
but not
__str__,
Python can use the representation provided by
__repr__
when a string representation is requested.
__len__: Supporting len()
The
__len__
method tells Python how to determine an object's length when
len()
is called.
class ShoppingCart:
def __init__(self):
self.items = []
def add_item(self, item: str):
self.items.append(item)
def __len__(self):
return len(self.items)
cart = ShoppingCart()
cart.add_item("Keyboard")
cart.add_item("Mouse")
print(len(cart))
The custom class now behaves naturally with
len()
because it defines what "length" means for that object.
__bool__: Controlling Truthiness
The
__bool__
method controls how an object behaves in a boolean context such as
if obj.
class ShoppingCart:
def __init__(self):
self.items = []
def add_item(self, item: str):
self.items.append(item)
def __bool__(self):
return bool(self.items)
cart = ShoppingCart()
if not cart:
print("Cart is empty")
cart.add_item("Keyboard")
if cart:
print("Cart contains items")
When an object does not define
__bool__,
Python can use
__len__
for truth-value testing if it is available.
__eq__: Custom Equality
The
__eq__
method defines how two objects should be compared using
==.
class Product:
def __init__(self, product_id: int):
self.product_id = product_id
def __eq__(self, other):
if not isinstance(other, Product):
return NotImplemented
return self.product_id == other.product_id
first = Product(101)
second = Product(101)
third = Product(202)
print(first == second)
print(first == third)
Returning
NotImplemented
for an unsupported comparison is generally preferable to forcing the comparison to return
False,
because Python can then give the other operand an opportunity to participate in the comparison.
Comparison Magic Methods
Python provides special methods for other comparison operators as well:
| Operator | Method |
|---|---|
== |
__eq__ |
!= |
__ne__ |
< |
__lt__ |
<= |
__le__ |
> |
__gt__ |
>= |
__ge__ |
Arithmetic Magic Methods
Custom classes can define arithmetic behavior using special methods. This is commonly called operator overloading.
| Operator | Special Method |
|---|---|
+ |
__add__ |
- |
__sub__ |
* |
__mul__ |
/ |
__truediv__ |
// |
__floordiv__ |
% |
__mod__ |
** |
__pow__ |
class Money:
def __init__(self, amount: float):
self.amount = amount
def __add__(self, other):
if not isinstance(other, Money):
return NotImplemented
return Money(
self.amount + other.amount
)
first = Money(100)
second = Money(50)
total = first + second
print(total.amount)
Operator overloading should only be used when the operator has an intuitive meaning for the domain. If
+
means something surprising, a normal method such as
combine()
may be clearer.
Reverse Arithmetic Methods
Python also provides reverse special methods such as
__radd__,
__rsub__,
and
__rmul__.
These can participate when the custom object appears on the right-hand side of an operation.
class Score:
def __init__(self, value: int):
self.value = value
def __radd__(self, other):
if not isinstance(other, int):
return NotImplemented
return other + self.value
score = Score(10)
print(5 + score)
Understanding reflected operations becomes particularly useful when designing numeric or value-like classes.
__getitem__: Supporting Indexing
The
__getitem__
method allows an object to respond to subscription syntax such as
obj[key].
class Playlist:
def __init__(self, songs: list[str]):
self.songs = songs
def __getitem__(self, index):
return self.songs[index]
playlist = Playlist([
"Song A",
"Song B",
"Song C"
])
print(playlist[0])
print(playlist[1])
Because the implementation forwards indexing to the internal list, normal indexing and slicing behavior can work naturally.
__setitem__ and __delitem__
Related special methods allow custom objects to support item assignment and deletion.
class Settings:
def __init__(self):
self.data = {}
def __getitem__(self, key):
return self.data[key]
def __setitem__(self, key, value):
self.data[key] = value
def __delitem__(self, key):
del self.data[key]
settings = Settings()
settings["theme"] = "dark"
print(settings["theme"])
del settings["theme"]
This allows a custom object to provide dictionary-like syntax when that syntax naturally represents the domain.
__iter__ and __next__
The
__iter__
method defines how an object provides an iterator. Iterators themselves generally implement
__next__
to produce values one at a time and raise
StopIteration
when there are no more values.
class NumberCollection:
def __init__(self, numbers: list[int]):
self.numbers = numbers
def __iter__(self):
return iter(self.numbers)
numbers = NumberCollection([10, 20, 30])
for number in numbers:
print(number)
When a
for
loop receives this object, Python asks it for an iterator through the iteration protocol.
Creating a Custom Iterator
When an object itself needs to maintain iterator state, it can implement both
__iter__
and
__next__.
class Counter:
def __init__(self, limit: int):
self.limit = limit
self.current = 0
def __iter__(self):
return self
def __next__(self):
if self.current >= self.limit:
raise StopIteration
value = self.current
self.current += 1
return value
counter = Counter(3)
for value in counter:
print(value)
The loop repeatedly calls
__next__()
until
StopIteration
signals that iteration is complete.
__contains__: Supporting in
The
__contains__
method customizes membership testing with the
in
operator.
class PermissionSet:
def __init__(self, permissions: set[str]):
self.permissions = permissions
def __contains__(self, permission: str) -> bool:
return permission in self.permissions
permissions = PermissionSet({
"users.read",
"users.write"
})
print("users.read" in permissions)
print("users.delete" in permissions)
__call__: Making an Object Callable
Normally, parentheses after a variable are used to call a function. A class can implement
__call__
to make its instances callable as well.
class Multiplier:
def __init__(self, factor: int):
self.factor = factor
def __call__(self, value: int) -> int:
return value * self.factor
double = Multiplier(2)
print(double(10))
print(double(25))
Callable objects can be useful for strategies, validators, configurable transformations, and other objects that represent reusable operations with internal state.
__enter__ and __exit__: Context Managers
Objects used with the
with
statement can implement
__enter__
and
__exit__.
This allows resources or temporary state to be prepared and cleaned up reliably.
class Connection:
def __enter__(self):
print("Connection opened")
return self
def __exit__(
self,
exc_type,
exc_value,
traceback
):
print("Connection closed")
with Connection() as connection:
print("Working with connection")
The
__exit__
method receives information about an exception when one occurs inside the
with
block. Its return value can be used to indicate whether an exception should be suppressed.
__new__ vs __init__
The distinction between
__new__
and
__init__
is a common Python interview question.
| Method | Role |
|---|---|
__new__ |
Creates and returns the instance. |
__init__ |
Initializes the already-created instance. |
Most application code only needs
__init__.
Customizing
__new__
is an advanced technique used for cases such as immutable types, object creation control, or specialized construction behavior.
__hash__ and Hashable Objects
The
__hash__
method is related to using objects as keys in dictionaries or elements in sets. Hashing must agree with equality: objects that compare equal should have compatible hash values.
This is why mutability matters. If an object's hash-relevant state changes while the object is stored in a set or used as a dictionary key, lookup behavior can become incorrect. Value-like immutable objects are generally safer candidates for hashing.
Rich Comparison with total_ordering
Python's
functools.total_ordering
decorator can help generate missing ordering methods when a class supplies
__eq__
and one ordering operation such as
__lt__.
from functools import total_ordering
@total_ordering
class Score:
def __init__(self, points: int):
self.points = points
def __eq__(self, other):
if not isinstance(other, Score):
return NotImplemented
return self.points == other.points
def __lt__(self, other):
if not isinstance(other, Score):
return NotImplemented
return self.points < other.points
first = Score(70)
second = Score(90)
print(first < second)
print(first <= second)
print(first != second)
This can reduce repetitive comparison implementations, although explicitly implementing the needed operations can sometimes provide clearer behavior or better performance.
Special Methods and Python Protocols
Many magic methods are part of broader Python protocols. A protocol describes how an object participates in a language feature. For example, defining
__iter__
allows an object to participate in iteration, while
__enter__
and
__exit__
allow it to participate in the context manager protocol.
Thinking in terms of protocols helps you understand why Python can work with objects based on what they support rather than requiring every object to inherit from a specific class.
A Practical Domain Example
Consider a
Cart
object. Magic methods can make it feel natural to use while keeping the actual implementation inside the class.
class Cart:
def __init__(self, items=None):
self.items = list(items or [])
def __len__(self):
return len(self.items)
def __iter__(self):
return iter(self.items)
def __getitem__(self, index):
return self.items[index]
def __contains__(self, item):
return item in self.items
def __str__(self):
return f"Cart with {len(self)} items"
def __add__(self, other):
if not isinstance(other, Cart):
return NotImplemented
return Cart(self.items + other.items)
first = Cart(["Keyboard", "Mouse"])
second = Cart(["Monitor"])
combined = first + second
print(combined)
print(len(combined))
print(combined[0])
for item in combined:
print(item)
print("Mouse" in combined)
The class now integrates naturally with several parts of Python's syntax. Users of the class do not need to call methods such as
__getitem__
or
__iter__
directly.
Do Not Call Magic Methods Unnecessarily
Special methods are designed primarily for Python's data model and language operations. You normally should write:
print(user)
len(cart)
item in collection
first + second
rather than manually calling:
user.__str__()
cart.__len__()
collection.__contains__(item)
first.__add__(second)
Direct calls can be useful for debugging or specialized implementation work, but normal application code should generally use the corresponding Python operation.
Common Mistakes
Returning the Wrong Type
Special methods often have specific return requirements. For example, __str__ must return a string and __len__ must provide a valid non-negative length.
Misusing Operators
Overloading + or comparison operators with surprising semantics can make a class harder to understand.
Forgetting NotImplemented
For unsupported operand types, returning NotImplemented can allow Python's operator dispatch to handle the other operand appropriately.
Implementing Too Many Methods
Only implement special methods that make your object's behavior more natural or satisfy a real protocol requirement.
Best Practices for Magic Methods
- Implement special methods when they make an object behave naturally with Python syntax.
- Keep the semantics of overloaded operators intuitive.
- Return values with the types expected by the corresponding protocol.
- Return
NotImplementedfor unsupported operand combinations where appropriate. - Keep
__str__readable and__repr__useful for debugging. - Use
__iter__and related methods only when iteration genuinely represents the object. - Use context-manager methods when the object owns setup and cleanup responsibilities.
- Be careful with equality and hashing, especially for mutable objects.
- Prefer clear normal methods when a magic method would make the API surprising.
Interview Questions to Prepare
- What are magic methods or dunder methods in Python?
- What is the difference between
__new__and__init__? - What is the difference between
__str__and__repr__? - How does
len()work with custom objects? - What does
__call__do? - How do
__iter__and__next__implement iteration? - How does operator overloading work in Python?
- Why should a comparison or arithmetic method sometimes return
NotImplemented? - How do
__enter__and__exit__support thewithstatement? - What is the relationship between
__eq__and__hash__?
Summary
Python magic methods connect custom objects to Python's built-in language features. Methods such as
__init__,
__str__,
__repr__,
__len__,
__getitem__,
__iter__,
__call__,
and
__enter__
allow objects to participate naturally in object creation, printing, collections, iteration, function calls, operators, and context managers.
The key is to treat special methods as part of Python's data model rather than as tricks. Choose methods that express a genuine relationship between your object and a Python operation, keep their behavior predictable, and avoid adding magic simply for the sake of abstraction.