Understanding Python Magic Methods: A Comprehensive Guide
This article explains Python's magic (dunder) methods, detailing their purpose, common special methods for initialization, comparison, arithmetic, container protocols, and other operations, and provides a practical code example to illustrate how they enable custom class behavior.
Python is a flexible and powerful language, and its magic methods—also known as special or dunder methods—allow developers to finely control class behavior by defining methods that Python internally invokes for operations such as object creation, representation, comparison, arithmetic, and container protocols.
What are magic methods? They are predefined methods whose names start and end with double underscores (e.g., __init__ , __add__ ) and are automatically called by Python to implement specific behaviors.
Common special methods overview
Object initialization and representation
__init__(self, ...) : constructor for initializing objects.
__del__(self) : destructor executed when an object is destroyed.
__str__(self) : returns a readable string representation for print() .
__repr__(self) : returns an official string representation for debugging.
Comparison operations
__eq__(self, other) : defines behavior of == .
__ne__(self, other) : defines behavior of != .
__lt__(self, other) : defines behavior of < .
__le__(self, other) : defines behavior of <= .
__gt__(self, other) : defines behavior of > .
__ge__(self, other) : defines behavior of >= .
Arithmetic operations
__add__(self, other) : defines + behavior.
__sub__(self, other) : defines - behavior.
__mul__(self, other) : defines * behavior.
__truediv__(self, other) : defines / behavior.
__floordiv__(self, other) : defines // behavior.
__mod__(self, other) : defines % behavior.
__pow__(self, other) : defines ** behavior.
Container type protocols
__len__(self) : returns number of items.
__getitem__(self, key) : retrieves an item.
__setitem__(self, key, value) : sets an item.
__delitem__(self, key) : deletes an item.
__iter__(self) : returns an iterator.
__contains__(self, item) : checks membership.
Other useful methods
__call__(self, ...) : makes an instance callable like a function.
__getattr__(self, name) : called when accessing a missing attribute.
__setattr__(self, name, value) : called when setting an attribute.
__getattribute__(self, name) : called for any attribute access.
Application scenarios
Customizing class behavior such as comparisons, arithmetic, and iteration.
Simulating built‑in types to create custom containers.
Implementing advanced features like context managers and decorators.
Code example
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 __str__(self):
return f"Vector({self.x}, {self.y})"
v1 = Vector(1, 2)
v2 = Vector(3, 4)
print(v1 + v2) # 输出: Vector(4, 6)Mastering these magic methods gives deeper insight into Python’s object‑oriented mechanisms and enables writing more elegant, powerful code.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.