0
0
PythonConceptBeginner · 4 min read

All Magic Methods in Python: Complete List and Usage

In Python, magic methods are special methods with double underscores before and after their names, like __init__ or __str__. They let you customize how objects behave with built-in operations such as creation, printing, arithmetic, and comparisons.
⚙️

How It Works

Magic methods in Python are like secret hooks that let you change how your objects act in different situations. Imagine your object is a robot, and magic methods are buttons you press to make it do special things automatically, like saying hello when you ask for its name or adding two robots together.

These methods always have double underscores before and after their names, such as __init__ for setting up a new object or __add__ for adding two objects. Python calls these methods behind the scenes when you use operators or built-in functions, so you don’t have to call them directly.

💻

Example

This example shows a simple class that uses magic methods to customize how objects are created, printed, and added together.

python
class Number:
    def __init__(self, value):
        self.value = value

    def __str__(self):
        return f"Number({self.value})"

    def __add__(self, other):
        if isinstance(other, Number):
            return Number(self.value + other.value)
        return NotImplemented

num1 = Number(5)
num2 = Number(10)
num3 = num1 + num2
print(num1)  # Calls __str__
print(num3)  # Calls __add__ and then __str__
Output
Number(5) Number(15)
🎯

When to Use

Use magic methods when you want your objects to work naturally with Python’s built-in features. For example, use __init__ to set up new objects, __str__ or __repr__ to control how objects print, and __add__ or __eq__ to define how objects add or compare.

This is helpful when creating custom data types, like points in a game, bank accounts, or complex numbers, so they behave like normal Python types.

Key Points

  • Magic methods have names with double underscores, like __init__ or __len__.
  • They let you customize object creation, representation, arithmetic, comparison, and more.
  • Python calls them automatically during operations like printing, adding, or comparing.
  • Implementing magic methods makes your objects integrate smoothly with Python’s syntax and functions.

Key Takeaways

Magic methods customize how Python objects behave with built-in operations.
They always have double underscores before and after their names.
Common magic methods include __init__, __str__, __add__, and __eq__.
Use them to make your custom objects act like built-in types.
Python calls magic methods automatically during relevant operations.