Python Advance Course
Magic Methods (Dunder Methods) in Python
Magic Methods (Dunder Methods) in Python
Magic methods (also called dunder methods) are special methods in Python surrounded by double underscores __.
They allow you to define how objects behave with: - built-in functions - operators - loops - printing - object creation
Why Magic Methods?
They allow custom classes to behave like built-in types.
Example idea:
- + works for numbers → we can define it for objects too
- len() works for strings → we can define it for custom objects
1. __init__() (Constructor)
Used to initialize object values.
Example:
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
s = Student("Aman", 20)
print(s.name, s.age)
Output:
Aman 20
Real-world example: - Creating user accounts - Initializing product details
Common Mistake
class A:
def __init__():
pass
Error:
- missing self
Correct:
def __init__(self):
Homework:
Create a class Car with brand and price.
Solution:
class Car:
def __init__(self, brand, price):
self.brand = brand
self.price = price
c = Car("Toyota", 500000)
print(c.brand, c.price)
2. __str__() (User-friendly string)
Used for readable output.
Example:
class Student:
def __init__(self, name):
self.name = name
def __str__(self):
return f"Student: {self.name}"
s = Student("Aman")
print(s)
Output:
Student: Aman
Real-world: - Displaying user info in UI - Printing objects cleanly
3. __repr__() (Developer representation)
Used for debugging and technical representation.
Example:
class Student:
def __init__(self, name):
self.name = name
def __repr__(self):
return f"Student(name='{self.name}')"
s = Student("Aman")
print(repr(s))
Output:
Student(name='Aman')
Difference: __str__ vs __repr__
| Method | Purpose | Audience |
|---|---|---|
| __str__ | readable output | user |
| __repr__ | debugging info | developer |
4. __len__() (Length behavior)
Used with len() function.
Example:
class Box:
def __init__(self, items):
self.items = items
def __len__(self):
return len(self.items)
b = Box([1, 2, 3, 4])
print(len(b))
Output:
4
Real-world: - Shopping cart items - Inventory count
5. __iter__() (Iteration support)
Used in loops (for loop support).
Example:
class Numbers:
def __init__(self):
self.data = [1, 2, 3]
def __iter__(self):
return iter(self.data)
n = Numbers()
for i in n:
print(i)
Output:
1
2
3
Real-world: - Database rows - API response iteration
6. __add__() (Operator overloading)
Defines behavior of + operator.
Example:
class Number:
def __init__(self, value):
self.value = value
def __add__(self, other):
return self.value + other.value
a = Number(10)
b = Number(20)
print(a + b)
Output:
30
Real-world: - Adding money objects - Combining vectors - Merging data
Graph (Operator Flow)
a + b
↓
a.__add__(b)
↓
custom logic runs
Combined Example (All Magic Methods)
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
def __str__(self):
return f"{self.name} - {self.price}"
def __repr__(self):
return f"Product(name='{self.name}', price={self.price})"
def __len__(self):
return len(self.name)
def __add__(self, other):
return self.price + other.price
p1 = Product("Phone", 10000)
p2 = Product("Laptop", 50000)
print(p1)
print(repr(p1))
print(len(p1))
print(p1 + p2)
Real World Mapping
| Magic Method | Real Use |
|---|---|
| __init__ | object creation |
| __str__ | UI display |
| __repr__ | debugging |
| __len__ | counting items |
| __iter__ | loops |
| __add__ | combining objects |
Common Mistakes
1. Missing self
def __init__():
2. Wrong return type
def __len__(self):
return "10"
3. Forgetting iterator return
def __iter__(self):
pass
Homework 1
Create a class Cart:
- store items
- support len()
- support iteration
Solution:
class Cart:
def __init__(self, items):
self.items = items
def __len__(self):
return len(self.items)
def __iter__(self):
return iter(self.items)
c = Cart(["apple", "banana", "mango"])
print(len(c))
for item in c:
print(item)
Homework 2
Create a class Money:
- support addition using __add__
Solution:
class Money:
def __init__(self, amount):
self.amount = amount
def __add__(self, other):
return self.amount + other.amount
a = Money(100)
b = Money(200)
print(a + b)
Graph (Magic Method System)
Object
↓
Magic Method Triggered
↓
Python internal behavior overridden
Next Advanced Topics
- Decorators (deep chaining)
- Context Managers (__enter__, __exit__)
- Iterators & Generators
- Descriptor Protocol
- Metaclasses (very advanced OOP)
- Data classes (@dataclass) ```