Magic Method

In Python, magic methods, also known as dunder (double underscore) methods, are special methods that you can define in your classes to enable and customize the behavior of your objects.

These methods allow you to define how your objects behave with built-in functions and operators. For example, you can use magic methods to define how your objects are compared, how they are represented as strings, how they support iteration, and much more. Special methods also play an important role in supporting internal Python protocols, such as the iterator, descriptor, and context manager protocols.

Magic methods are characterized by their double underscores before and after their names, such as .__init__(), .__str__(), .__len__(), and .__add__(). Each of these methods corresponds to a specific operation. For example, .__init__() is called when you create a new instance of a class, .__str__() is called by the built-in str() function to get a string representation of an object, and .__add__() allows you to define the behavior of the addition operator +.

Example

Here’s an example of using the .__init__(), .__add__(), and .__repr__() methods:

Python
>>> class Point:
...     def __init__(self, x, y):
...         self.x = x
...         self.y = y
...     def __add__(self, other):
...         return Point(self.x + other.x, self.y + other.y)
...     def __repr__(self):
...         return f"Point({self.x}, {self.y})"
...

>>> p1 = Point(1, 2)
>>> p2 = Point(3, 4)
>>> p3 = p1 + p2
>>> p3
Point(4, 6)

In this example, the __init__() method initializes every instance of the Point class. The .__add__() method makes your Point objects support addition using the + operator. The .__repr__() method provides a developer-friendly string representation of the Point object.

Tutorial

Python's Magic Methods: Leverage Their Power in Your Classes

In this tutorial, you'll learn what magic methods are in Python, how they work, and how to use them in your custom classes to support powerful features in your object-oriented code.

advanced python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Dec. 19, 2024 • Reviewed by Dan Bader