Dunder or Magic Methods

Python's __magic__ (or dunder) methods are special methods that start and end with double underscores. They're used to implement operator overloading and to define the behavior of custom classes with built-in functions.

Here’s a list of useful and commonly encountered magic methods:


πŸ”§ Object Construction & Representation

Method Purpose
__init__(self, ...) Constructor. Initializes the object.
__new__(cls, ...) Allocates memory; rarely overridden.
__str__(self) Human-readable string (str(obj), print(obj)).
__repr__(self) Official string (repr(obj) or in REPL).
__del__(self) Destructor (not commonly used).

πŸ” Operator Overloading

Method Operator Example
__add__(self, other) + a + b
__sub__(self, other) - a - b
__mul__(self, other) * a * b
__truediv__(self, other) / a / b
__floordiv__(self, other) // a // b
__mod__(self, other) % a % b
__pow__(self, other) ** a ** b
__eq__(self, other) == a == b
__lt__(self, other) < a < b
__le__(self, other) <= a <= b

πŸ“¦ Container Behavior

Method Purpose
__len__(self) Length of the object (len(obj))
__getitem__(self, key) Indexing (obj[key])
__setitem__(self, key, value) Item assignment (obj[key] = value)
__delitem__(self, key) Delete item (del obj[key])
__iter__(self) Returns an iterator (for x in obj)
__next__(self) Next value in iteration (next(obj))
__contains__(self, item) in keyword (item in obj)

🎩 Callable & Context Manager

Method Purpose
__call__(self, ...) Make an object callable like a function (obj())
__enter__(self) Context manager (with statement entry)
__exit__(self, exc_type, exc_val, exc_tb) Context manager (with statement exit)

πŸ’‘ Example: Custom Class with Magic Methods

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 __str__(self):
        return f"Point({self.x}, {self.y})"

p1 = Point(1, 2)
p2 = Point(3, 4)
print(p1 + p2)  # Uses __add__

Thanks for Stopping by! Happy learning

Connect with me on

GithubΒ LinkedInΒ GmailΒ Youtube