Thuta Learning
IntermediateProgrammingbeginner

Magic Methods (Enhanced)

Relax. We'll talk through this in plain words — no textbook voice.

🎩 Lesson 6: Magic Methods (Dunder Methods)

1. What are magic methods?

In short → Magic methods (dunder methods) are hooks that integrate Python objects with builtin syntax. __init__, __str__, __len__ and other double-underscore methods enable/customize features like construction, printing, arithmetic, comparisons, iteration, and context management.

In detail → Magic methods (dunder methods) are hooks that integrate Python objects with builtin syntax. Double-underscore methods enable/customize features like construction, printing, arithmetic, comparisons, iteration, and context management.

2. Common Magic Methods

CategoryMethods
Lifecycle__init__, __new__, __del__
Representation__repr__, __str__, __format__
Arithmetic__add__, __sub__, __mul__, __truediv__
Containers__len__, __getitem__, __iter__

3. Summary

✅ Magic methods let classes play nicely with Python's syntax

✅ Use them to make APIs intuitive and Pythonic

✅ Prioritize correctness, clarity, and performance

python
# ===== 1. Initialization and Representation =====
class User:
    def __init__(self, name, age):        # constructor
        self.name = name
        self.age = age

    def __repr__(self):                   # unambiguous, for developers
        return f"User(name={self.name!r}, age={self.age})"

    def __str__(self):                    # human-friendly
        return f"{self.name} ({self.age})"

u = User("Sai", 25)
print(f"__repr__: {repr(u)}")
print(f"__str__: {str(u)}")

# ===== 2. Arithmetic Operators =====
class Vector:
    def __init__(self, x, y):
        self.x, self.y = x, y

    def __add__(self, other):             # v1 + v2
        return Vector(self.x + other.x, self.y + other.y)

    def __repr__(self):
        return f"Vector({self.x}, {self.y})"

v1 = Vector(1, 2)
v2 = Vector(3, 4)
print(f"\nv1 + v2 = {v1 + v2}")

# ===== 3. Container Methods =====
class Bag:
    def __init__(self, items):
        self._items = list(items)

    def __len__(self):                     # len(bag)
        return len(self._items)

    def __getitem__(self, idx):            # bag[0]
        return self._items[idx]

    def __iter__(self):                    # for x in bag
        return iter(self._items)

bag = Bag([1, 2, 3, 4])
print(f"\nlen(bag) = {len(bag)}")
print(f"bag[0] = {bag[0]}")
print(f"Iteration: {[x for x in bag]}")
You should see
__repr__: User(name='Sai', age=25) __str__: Sai (25) v1 + v2 = Vector(4, 6) len(bag) = 4 bag[0] = 1 Iteration: [1, 2, 3, 4]
Magic Methods (Enhanced) | Thuta Learning