Ad – 728Γ—90
πŸ—οΈ OOP

Python Magic Methods – Dunder Methods Explained

Magic methods (also called dunder methods β€” double underscore) are special Python methods that define how objects behave with built-in operations. They let you define what happens when you print an object, add two objects, compare them, use them in a with statement, or iterate over them.

⏱️ 22 min read🎯 AdvancedπŸ“… Updated 2026

__str__ and __repr__

__str__: human-readable string (for print). __repr__: developer representation (unambiguous, for debugging).

Python
class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y

    def __str__(self):
        return f"Point({self.x}, {self.y})"

    def __repr__(self):
        return f"Point(x={self.x!r}, y={self.y!r})"

p = Point(3, 4)
print(str(p))   # Point(3, 4)      β€” uses __str__
print(repr(p))  # Point(x=3, y=4)  β€” uses __repr__
print(p)        # Point(3, 4)      β€” print uses __str__
β–Ά Output
Point(3, 4) Point(x=3, y=4) Point(3, 4)

Comparison Methods

Define how objects are compared with ==, <, >, <=, >= operators.

Python
class Temperature:
    def __init__(self, celsius):
        self.celsius = celsius

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

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

    def __le__(self, other):
        return self.celsius <= other.celsius

t1 = Temperature(25)
t2 = Temperature(30)

print(t1 == t2)   # False
print(t1 < t2)    # True
temps = [Temperature(30), Temperature(10), Temperature(20)]
print([t.celsius for t in sorted(temps)])  # [10, 20, 30]
β–Ά Output
False True [10, 20, 30]

Arithmetic Methods

Make + - * / work on your objects.

Python
class Money:
    def __init__(self, amount, currency="USD"):
        self.amount = amount
        self.currency = currency

    def __add__(self, other):
        if self.currency != other.currency:
            raise ValueError("Cannot add different currencies")
        return Money(self.amount + other.amount, self.currency)

    def __str__(self):
        return f"{self.currency} {self.amount:.2f}"

wallet = Money(50) + Money(30)
print(wallet)   # USD 80.00
β–Ά Output
USD 80.00
Ad – 336Γ—280

Container Methods

__len__, __getitem__, __contains__ make custom objects behave like sequences.

Python
class Library:
    def __init__(self):
        self._books = []

    def add(self, book): self._books.append(book)
    def __len__(self): return len(self._books)
    def __getitem__(self, idx): return self._books[idx]
    def __contains__(self, book): return book in self._books

lib = Library()
lib.add("Python Crash Course")
lib.add("Fluent Python")

print(len(lib))                    # 2
print(lib[0])                      # Python Crash Course
print("Fluent Python" in lib)      # True
β–Ά Output
2 Python Crash Course True