0
0
Pythonprogramming~5 mins

Purpose of magic methods in Python

Choose your learning style9 modes available
Introduction

Magic methods let you change how your objects behave with built-in Python actions. They make your objects work like normal Python types.

When you want your object to add two instances using +
When you want to print your object nicely with print()
When you want to compare two objects with == or <
When you want your object to work with len() to get its size
When you want to customize what happens when your object is created or deleted
Syntax
Python
def __method_name__(self, other):
    # your code here

Magic methods always start and end with double underscores.

They are called automatically by Python in special situations.

Examples
This method controls what print() shows for your object.
Python
def __str__(self):
    return 'Nice string representation'
This method lets you use + to add two objects.
Python
def __add__(self, other):
    return self.value + other.value
This method lets you use len() on your object.
Python
def __len__(self):
    return len(self.items)
Sample Program

This program shows how magic methods __str__ and __add__ let us print boxes nicely and add their contents.

Python
class Box:
    def __init__(self, content):
        self.content = content
    def __str__(self):
        return f'Box with {self.content}'
    def __add__(self, other):
        return Box(self.content + ' & ' + other.content)

box1 = Box('Apples')
box2 = Box('Oranges')
print(box1)
print(box2)
box3 = box1 + box2
print(box3)
OutputSuccess
Important Notes

Magic methods let your objects feel like built-in types.

You don't call magic methods directly; Python calls them for you.

Using magic methods makes your code cleaner and easier to use.

Summary

Magic methods customize how objects behave with Python features.

They always have double underscores before and after their name.

Common magic methods include __init__, __str__, __add__, and __len__.