- Courses
- 💻Programming Languages
- 🐍Python
- Object‑Oriented Programming (OOP)
- Magic Methods
On this page
Magic Methods
By Enrico Hochkoeppler
Web Developer & TutoriaLibre Founder
What Magic Methods Are
Magic methods (also called dunder methods, because they use double underscores) are special methods that allow your objects to interact naturally with Python’s syntax and built‑in operations.
They enable features such as:
- Object construction
- String representation
- Arithmetic operators
- Comparisons
- Iteration
- Context managers
Magic methods let your classes behave like native Python types, making them intuitive and powerful.
Magic methods are not called directly. Python calls them automatically when specific operations occur.
Object Construction and Initialization
Two essential magic methods control object creation:
__new__ — Object Creation
Responsible for creating a new instance. Rarely overridden except in advanced scenarios.
__init__ — Object Initialization
Initializes the newly created object.
class Person:
def __init__(self, name):
self.name = name
Python calls __init__ automatically after creating the object.
String Representation
Magic methods define how an object is represented as text.
__str__ — User‑Friendly Representation
Used by print() and str().
def __str__(self):
return f"Person({self.name})"
__repr__ — Unambiguous Representation
Used by developers and debugging tools.
def __repr__(self):
return f"Person(name={self.name!r})"
Best practice: __repr__ should return a string that could recreate the object if possible.
Arithmetic Operator Methods
Magic methods allow objects to support arithmetic operations.
Addition
def __add__(self, other):
...
Subtraction
def __sub__(self, other):
...
Multiplication
def __mul__(self, other):
...
Example: a simple vector class.
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __repr__(self):
return f"Vector({self.x}, {self.y})"
Now:
Vector(1, 2) + Vector(3, 4)
works naturally.
Comparison Methods
Magic methods define how objects compare to each other.
__eq__(self, other)— equality__ne__(self, other)— inequality__lt__(self, other)— less than__le__(self, other)— less than or equal__gt__(self, other)— greater than__ge__(self, other)— greater than or equal
Example:
def __eq__(self, other):
return (self.x, self.y) == (other.x, other.y)
Implementing comparisons makes objects sortable and comparable.
Container and Sequence Behavior
Magic methods allow objects to behave like lists, dictionaries, or other containers.
Length
def __len__(self):
return len(self.items)
Indexing
def __getitem__(self, index):
return self.items[index]
Assignment
def __setitem__(self, index, value):
self.items[index] = value
Membership
def __contains__(self, item):
return item in self.items
These methods make custom containers integrate seamlessly with Python’s data model.
Iteration Support
To make an object iterable:
__iter__
Returns an iterator.
__next__
Returns the next item.
Example:
class Counter:
def __init__(self, limit):
self.limit = limit
self.current = 0
def __iter__(self):
return self
def __next__(self):
if self.current < self.limit:
value = self.current
self.current += 1
return value
raise StopIteration
Now the object works in loops:
for n in Counter(3):
print(n)
Callable Objects
Objects can behave like functions by defining:
def __call__(self, *args, **kwargs):
...
Example:
class Greeter:
def __call__(self, name):
return f"Hello, {name}"
Usage:
g = Greeter()
g("Alice")
Context Manager Support
Magic methods allow objects to be used with with statements.
__enter__— setup__exit__— cleanup
Example:
class Resource:
def __enter__(self):
print("Opening resource")
return self
def __exit__(self, exc_type, exc, tb):
print("Closing resource")
Usage:
with Resource():
...
Best Practices for Magic Methods
- Implement magic methods only when they make the class more intuitive
- Ensure behavior matches user expectations
- Keep implementations simple and predictable
- Prefer
__repr__for debugging and__str__for user‑facing output - Use arithmetic and comparison methods only when they make conceptual sense
- Avoid overusing magic methods; clarity is more important than cleverness
Summary
In this lesson, you learned how magic methods allow Python objects to integrate with the language’s syntax and built‑in operations. You explored initialization, representation, arithmetic, comparisons, container behavior, iteration, callability, and context managers. Magic methods are a powerful tool for designing expressive, Pythonic classes that behave like native types.
Found this helpful? Share the knowledge...
... or support this project to keep it alive!
Previous
Encapsulation
Next
Guided Exercise: Build a Mini RPG Class System
-
What Magic Methods Are
-
Object Construction and Initialization
__new__— Object Creation__init__— Object Initialization
-
String Representation
__str__— User‑Friendly Representation__repr__— Unambiguous Representation
-
Arithmetic Operator Methods
- Addition
- Subtraction
- Multiplication
-
Comparison Methods
-
Container and Sequence Behavior
- Length
- Indexing
- Assignment
- Membership
-
Iteration Support
__iter____next__
-
Callable Objects
-
Context Manager Support
-
Best Practices for Magic Methods
-
Summary
