# Magic Methods (Dunder Methods)

> Magic methods (also called dunder methods, short for double underscore) are special methods with names surrounded by double underscores. They let you hook...

Canonical: https://www.internhack.in/learn/python/oop/magic-methods
Last updated: 2026-11-28

Difficulty: Intermediate

Magic methods (also called dunder methods, short for double underscore) are special methods with names surrounded by double underscores. They let you hook into Python's built-in behavior and make your custom objects work with operators, built-in functions, and language constructs like for-loops and with-statements. They are never called directly by name; instead, Python calls them automatically when you use the corresponding syntax.

\__str_\_ and \__repr_\_ control how your objects are converted to strings. \__str_\_ is called by print() and str() and should return a human-friendly description. \__repr_\_ is called by the interactive interpreter and repr(), and should ideally return a string that could recreate the object. If only one is defined, Python falls back from \__str_\_ to \__repr_\_ (but not vice versa), so if you define only one, make it \__repr_\_.

\__eq_\_ and \__lt_\_ are comparison methods. \__eq_\_ defines behavior for == and should return True or False. Without \__eq_\_, Python defaults to identity comparison (same as 'is'). \__lt_\_ defines behavior for < and, when combined with the functools.total_ordering decorator, can auto-generate <=, >, and >= as well. These methods are crucial for sorting and using your objects in sets or as dictionary keys.

\__len_\_ and \__getitem_\_ make your object behave like a collection. \__len_\_ is called by the len() function. \__getitem_\_ is called when you use square bracket notation obj\[key\]. Implementing \__getitem_\_ also makes your object iterable (you can use it in a for-loop) because Python will call \__getitem_\_ with increasing integer indices until an IndexError is raised. For more control over iteration, implement \__iter_\_ and \__next_\_ instead.

\__add_\_, \__sub_\_, \__mul_\_, and other arithmetic dunder methods define how operators work with your objects. \__add_\_ handles the + operator, \__sub_\_ handles -, and so on. There are also reflected versions like \__radd_\_ that are called when your object appears on the right side of the operator and the left object does not know how to handle the operation. These methods should return new objects rather than modifying the originals, consistent with how built-in types behave.

## Code examples

### \__str_\_ vs \__repr_\_

```
class Book:
    def __init__(self, title, author, pages):
        self.title = title
        self.author = author
        self.pages = pages

    def __str__(self):
        return f'{self.title} by {self.author}'

    def __repr__(self):
        return f"Book('{self.title}', '{self.author}', {self.pages})"

b = Book('1984', 'Orwell', 328)
print(str(b))
print(repr(b))
print(b)  # print calls __str__
```

\__str_\_ returns a readable description for end users. \__repr_\_ returns a detailed string that could recreate the object. print() calls \__str_\_ by default.

### \__eq_\_ and \__lt_\_ for comparison and sorting

```
class Student:
    def __init__(self, name, grade):
        self.name = name
        self.grade = grade

    def __eq__(self, other):
        return self.grade == other.grade

    def __lt__(self, other):
        return self.grade < other.grade

    def __repr__(self):
        return f'{self.name}:{self.grade}'

students = [Student('Alice', 88), Student('Bob', 95), Student('Charlie', 72)]
students.sort()
print(students)
print(Student('X', 88) == Student('Y', 88))
print(Student('X', 70) < Student('Y', 90))
```

sort() uses \__lt_\_ to order the students by grade. \__eq_\_ compares grades regardless of name, so two students with the same grade are considered equal. \__repr_\_ controls how they appear in the list printout.

### \__len_\_ and \__getitem_\_ for collection behavior

```
class Deck:
    def __init__(self):
        suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades']
        ranks = ['A', '2', '3']
        self.cards = [f'{r} of {s}' for s in suits for r in ranks]

    def __len__(self):
        return len(self.cards)

    def __getitem__(self, index):
        return self.cards[index]

deck = Deck()
print(len(deck))
print(deck[0])
print(deck[-1])
print(deck[2:5])
```

\__len_\_ lets len() work on the deck. \__getitem_\_ supports integer indexing, negative indexing, and slicing because Python's slice objects are passed directly to \__getitem_\_ and the internal list handles them.

### \__add_\_ and \__mul_\_ for arithmetic

```
class Matrix:
    def __init__(self, rows):
        self.rows = rows

    def __add__(self, other):
        result = []
        for r1, r2 in zip(self.rows, other.rows):
            result.append([a + b for a, b in zip(r1, r2)])
        return Matrix(result)

    def __mul__(self, scalar):
        result = [[val * scalar for val in row] for row in self.rows]
        return Matrix(result)

    def __repr__(self):
        return '\n'.join(str(row) for row in self.rows)

m1 = Matrix([[1, 2], [3, 4]])
m2 = Matrix([[5, 6], [7, 8]])
print(m1 + m2)
print('---')
print(m1 * 3)
```

\__add_\_ performs element-wise addition of two matrices. \__mul_\_ multiplies every element by a scalar. Both return new Matrix objects. \__repr_\_ formats the matrix row by row.

## Key points

- If you only define one of \__str_\_ or \__repr_\_, define \__repr_\_. Python falls back to \__repr_\_ when \__str_\_ is not defined, but not the other way around.
- Implementing \__getitem_\_ gives you basic iteration for free. Python will call \__getitem_\_(0), \__getitem_\_(1), etc. until IndexError.
- \__eq_\_ must be defined for your objects to work correctly in sets and as dict keys. You should also define \__hash_\_ if you define \__eq_\_.
- Use functools.total_ordering to auto-generate all comparison methods from just \__eq_\_ and one ordering method like \__lt_\_.

## Interview tips

- Know the key dunder method pairs: \__str_\_/\__repr_\_, \__eq_\_/\__hash_\_, \__lt_\_/\__le_\_/\__gt_\_/\__ge_\_, \__add_\_/\__radd_\_, \__len_\_/\__getitem_\_.
- Explain why \__repr_\_ is more important than \__str_\_: it is used in debugging, logging, and as a fallback for \__str_\_.
- Be prepared to implement a simple class with \__eq_\_, \__lt_\_, and \__repr_\_ that works with sorted(), sets, and print().

## Concepts covered

\__str_\_, \__repr_\_, \__len_\_, \__eq_\_, \__lt_\_, \__add_\_, \__getitem_\_, dunder methods

Previous: [Polymorphism](https://www.internhack.in/learn/python/oop/polymorphism) · [All of Object-Oriented Programming](https://www.internhack.in/learn/python/oop)

## More Object-Oriented Programming lessons

- [Inheritance](https://www.internhack.in/learn/python/oop/inheritance)
- [Encapsulation & Abstraction](https://www.internhack.in/learn/python/oop/encapsulation-abstraction)

## Related

- [Learn](https://www.internhack.in/learn)
- [Python](https://www.internhack.in/learn/python)
- [Object-Oriented Programming](https://www.internhack.in/learn/python/oop)
