What Are Magic Methods?
Magic methods (also called dunder methods for "double underscore") are special methods in Python that start and end with double underscores. They allow you to define how objects of your classes behave with language operators and built-in functions.
# Example of common magic methods
class MyClass:
def __init__(self, value):
self.value = value
def __str__(self):
return f"MyClass with value: {self.value}"
def __add__(self, other):
return MyClass(self.value + other.value)
Magic methods are the mechanism behind operator overloading and many of Python's built-in behaviors. They're not meant to be called directly, but invoked through specific language syntax.
Common Magic Methods
Here are some of the most frequently used magic methods:
# Initialization and representation
__init__: constructor
__new__: instance creation (before __init__)
__str__: informal string representation (str(obj), print(obj))
__repr__: official string representation (repr(obj))
# Comparison operators
__eq__: ==
__ne__: !=
__lt__: <
__gt__: >
__le__: <=
__ge__: >=
# Arithmetic operators
__add__: +
__sub__: -
__mul__: *
__truediv__: /
__floordiv__: //
__mod__: %
__pow__: **
Implementing these methods allows your objects to work naturally with Python's operators and built-in functions.
Container Magic Methods
These methods let your objects behave like containers (lists, dictionaries, etc.):
# Sequence/container behavior
__len__: len(obj)
__getitem__: obj[key]
__setitem__: obj[key] = value
__delitem__: del obj[key]
__contains__: item in obj
# Example implementation
class MyList:
def __init__(self, items):
self.items = items
def __getitem__(self, index):
return self.items[index]
def __len__(self):
return len(self.items)
def __contains__(self, item):
return item in self.items
With these methods, your objects can support indexing, slicing, iteration, and membership testing.
Context Manager Methods
These methods enable your objects to work with Python's 'with' statement:
# Context manager protocol
__enter__: called at start of 'with' block
__exit__: called at end of 'with' block
# Example implementation
class FileHandler:
def __init__(self, filename, mode):
self.filename = filename
self.mode = mode
def __enter__(self):
self.file = open(self.filename, self.mode)
return self.file
def __exit__(self, exc_type, exc_val, exc_tb):
self.file.close()
if exc_type is not None:
print(f"Exception occurred: {exc_val}")
return True # Suppress exception if True
Context managers are perfect for resource management (files, locks, database connections) that need proper setup and teardown.
Advanced Magic Methods
Some more specialized but powerful magic methods:
# Callable objects
__call__: makes instance callable like a function
# Attribute access
__getattr__: called when attribute not found
__setattr__: called when setting any attribute
__delattr__: called when deleting attribute
# Descriptor protocol
__get__, __set__, __delete__: for descriptor objects
# Numeric type emulation
__int__, __float__, __complex__: type conversion
__index__: for integer conversion (slicing, bin(), hex())
# Memory management
__del__: destructor (called when object is garbage collected)
These methods give you fine-grained control over object behavior and enable advanced Python features.
Python Magic Methods Videos
Master Python magic methods with these handpicked YouTube tutorials:
Customize operator behavior:
Powerful magic method patterns:
Real-world uses of magic methods: