Last modified: Dec 01, 2026
Python Magic Methods: Complete List
Python magic methods are special methods with double underscores. They start and end with __. People also call them dunder methods.
These methods let your objects work with built-in syntax. You can make objects addable, printable, and iterable. This guide lists the most useful ones with clear examples.
What Are Magic Methods?
Magic methods are hooks. Python calls them automatically in certain situations. You rarely call them directly.
For example, __init__ runs when you create an object. The __str__ method runs when you call print() on the object.
If you are new to classes, start with these class basics for beginners. Then come back here.
Object Creation and Setup
These methods control how objects are built and initialized.
__init__
This is the constructor. It sets up instance data after the object exists.
class Book:
def __init__(self, title):
self.title = title # Store the title
book = Book("Python Magic")
print(book.title)
Python Magic
Passing values to this method is common. See this guide on a Python class with arguments for more detail.
__new__
This method creates the object itself. It runs before __init__. You rarely need it.
Use it for immutable types or singletons. Most beginners can skip it.
String and Display Methods
These methods control how your object looks when printed or converted.
__str__
This returns a readable string. It is used by print() and str().
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f"Point({self.x}, {self.y})" # User-friendly output
print(Point(1, 2))
Point(1, 2)
__repr__
This returns an official string. It should ideally recreate the object. It is used in the console and by repr().
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return f"Point({self.x!r}, {self.y!r})" # Debug-friendly output
print(repr(Point(3, 4)))
Point(3, 4)
Comparison Methods
These methods let you compare objects with ==, <, and more.
__eq__
This method handles the == operator. It checks equality.
class Money:
def __init__(self, amount):
self.amount = amount
def __eq__(self, other):
return self.amount == other.amount # Compare values
print(Money(10) == Money(10))
True
__lt__
This method handles the < operator. It enables sorting.
class Money:
def __init__(self, amount):
self.amount = amount
def __lt__(self, other):
return self.amount < other.amount # Less-than logic
print(Money(5) < Money(8))
True
These comparison methods are part of the broader set of class methods and attributes you will use often.
Arithmetic Operator Methods
Magic methods let objects support math operators. Each operator maps to a method.
__add__
This method handles the + operator.
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) # Add vectors
def __repr__(self):
return f"Vector({self.x}, {self.y})"
print(Vector(1, 2) + Vector(3, 4))
Vector(4, 6)
__sub__, __mul__, __truediv__
These methods handle -, *, and /. They follow the same pattern as __add__.
You can also define in-place versions like __iadd__ for +=. And reflected versions like __radd__ for right-side operations.
Container and Length Methods
These methods make objects behave like collections.
__len__
This method handles len().
class Playlist:
def __init__(self, songs):
self.songs = songs
def __len__(self):
return len(self.songs) # Return item count
print(len(Playlist(["a", "b", "c"])))
3
__getitem__
This method handles indexing with square brackets.
class Playlist:
def __init__(self, songs):
self.songs = songs
def __getitem__(self, index):
return self.songs[index] # Support indexing
print(Playlist(["a", "b", "c"])[1])
b
Other useful container methods include __setitem__, __delitem__, and __contains__. They handle assignment, deletion, and the in keyword.
Iteration Methods
These methods let you loop over objects with for.
__iter__
This method returns an iterator. It powers the for loop.
class Countdown:
def __init__(self, start):
self.start = start
def __iter__(self):
n = self.start
while n > 0:
yield n # Yield each value
n -= 1
for num in Countdown(3):
print(num)
3
2
1
Context Manager Methods
These methods support the with statement.
__enter__ and __exit__
The __enter__ method runs at the start of a with block. The __exit__ method runs at the end, even on errors.
class Resource:
def __enter__(self):
print("Open") # Setup step
return self
def __exit__(self, exc_type, exc, tb):
print("Close") # Cleanup step
with Resource():
print("Working")
Open
Working
Close
Attribute Access Methods
These methods intercept attribute reads and writes. They are powerful but easy to misuse.
__getattr__ and __setattr__
The __getattr__ method runs when an attribute is missing. The __setattr__ method runs on every attribute assignment.
For most cases, properties are a safer choice. They give you controlled access without touching every attribute. Read this clear guide on class method examples to see practical patterns.
Properties and attributes often confuse beginners. If you want to know the difference, this comparison of property vs attribute helps a lot.
Properties also support setters and validation. That makes them a cleaner tool than raw magic methods for many tasks.
Callable Objects
The __call__ method lets an instance act like a function. You can call it with parentheses.
class Adder:
def __init__(self, n):
self.n = n
def __call__(self, x):
return x + self.n # Make instance callable
add_five = Adder(5)
print(add_five(10))
15
Quick Reference Table
Here is a short list of common magic methods and their purpose.
__init__ sets up objects. __str__ and __repr__ control display. __eq__ and __lt__ handle comparisons.
__add__ and friends handle math. __len__ and __getitem__ handle containers. __iter__ enables loops.
__enter__ and __exit__ enable context managers. __call__ makes objects callable. __getattr__ and __setattr__ control attribute access.
Best Practices
Keep magic methods simple. Each one should do one clear job.
Always define __repr__ for debugging. Define __str__ when users will print the object.
Do not overuse attribute hooks. Use properties for validation and computed values. They are easier to read and maintain.
Test your operators with edge cases. Check behavior with different types and empty values.
Common Mistakes
A common mistake is forgetting to return a value from __str__ or __repr__. Python expects a string.
Another mistake is defining __eq__ without __hash__. This can break dictionary keys. Set __hash__ = None if the object should not be hashable.
Also avoid calling dunder methods directly. Use the built-in functions and operators instead. Python will call the right method for you.
Conclusion
Python magic methods make your classes feel native. They connect your objects to Python syntax like printing, math, loops, and the with statement.
Start small. Add __init__, __repr__, and __eq__ first. Then add operators and containers only when needed.
Keep your code readable. Use properties for simple validation. Use magic methods for real syntax support. With practice, these methods will make your classes cleaner and more powerful.