- Learning Objectives
- Prerequisites
- Introduction
- What are Magic Methods?
- Why are Magic Methods Required?
- Why are they called Dunder Methods?
- How Magic Methods Work
- Common Magic Methods
- Operator Overloading
- Object Lifecycle
- Internal Working
- Summary
After completing this chapter, you will be able to:
- Understand Magic Methods.
- Understand Dunder Methods.
- Learn Python's built-in special methods.
- Understand Operator Overloading.
- Customize object behavior.
- Use Magic Methods in real-world applications.
Before learning this chapter, you should know:
- Classes
- Objects
- Constructors
- Methods
- Method Overloading
- Polymorphism
Everything in Python is an object.
Whenever we perform operations like
+
-
*
/
len()
print()
str()Python internally calls special methods.
For example,
a = 10
b = 20
print(a + b)Internally,
Python executes
a.__add__(b)Similarly,
print(obj)internally calls
obj.__str__()These special methods are called
Magic Methods
or
Dunder Methods.
Magic Methods are special predefined methods that begin and end with double underscores (__).
Python automatically invokes these methods in response to specific operations.
Magic Methods allow Python objects to respond to built-in operations such as addition, printing, comparison, iteration, and object creation.
Suppose we create a class
StudentWithout Magic Methods,
Python does not know
- How to print an object
- How to compare two objects
- How to add two objects
- How to calculate object length
Magic Methods define these behaviors.
"Dunder" means
Double
↓
Under
↓
Double Underscore
Examples
__init__()
__str__()
__len__()
__add__()Because they begin and end with
__
they are called
Dunder Methods.
Suppose
print(student)Python internally executes
student.__str__()Similarly,
len(student)becomes
student.__len__()Likewise,
student1 + student2becomes
student1.__add__(student2)Python automatically invokes these methods.
| Magic Method | Purpose |
|---|---|
__init__() |
Object Initialization |
__str__() |
User-Friendly String Representation |
__repr__() |
Official Object Representation |
__len__() |
Length of Object |
__add__() |
Addition |
__sub__() |
Subtraction |
__mul__() |
Multiplication |
__truediv__() |
Division |
__eq__() |
Equality Comparison |
__lt__() |
Less Than |
__gt__() |
Greater Than |
__contains__() |
Membership Test (in) |
__getitem__() |
Index Access |
__setitem__() |
Assign by Index |
__call__() |
Make Object Callable |
Magic Methods make Operator Overloading possible.
Example
student1 + student2internally becomes
student1.__add__(student2)Instead of only adding integers,
we can define what
+means for our own objects.
When an object is created,
Python follows this sequence
Object Created
↓
__new__()
↓
Memory Allocated
↓
__init__()
↓
Object Initialized
↓
Object Used
↓
Garbage Collected
Although __new__() exists,
beginners mainly work with
__init__()Operation
↓
Python Searches
↓
Corresponding Magic Method
↓
Method Executes
↓
Result Returned
Example
len(obj)
↓
obj.__len__()
↓
Length Returned
- Customizes object behavior.
- Enables Operator Overloading.
- Improves readability.
- Integrates with Python built-in functions.
- Makes classes behave like built-in types.
Magic Methods are used in:
- Django ORM
- NumPy
- Pandas
- TensorFlow
- SQLAlchemy
- PyTorch
- Data Structures
- Game Development
In this part, you learned:
- Magic Methods
- Dunder Methods
- Operator Overloading
- Object Lifecycle
- Internal Working
- Common Magic Methods
- Advantages
Write a Python program to demonstrate the __init__() method.
class Student:
def __init__(self, name):
self.name = name
student = Student("Rahul")
print(student.name)Rahul
__init__() is automatically called whenever an object is created.
It initializes the object.
Write a Python program to demonstrate the __str__() method.
class Student:
def __init__(self, name):
self.name = name
def __str__(self):
return f"Student(Name = {self.name})"
student = Student("Rahul")
print(student)Student(Name = Rahul)
When
print(student)is executed,
Python internally calls
student.__str__()It returns a user-friendly string representation.
Write a Python program to demonstrate the __repr__() method.
class Student:
def __init__(self, name):
self.name = name
def __repr__(self):
return f"Student('{self.name}')"
student = Student("Rahul")
print(repr(student))Student('Rahul')
__repr__() returns the official string representation of an object.
It is mainly used for debugging and development.
Write a Python program to demonstrate the __len__() method.
class Team:
def __init__(self):
self.players = ["Rahul", "Priya", "Kiran"]
def __len__(self):
return len(self.players)
team = Team()
print(len(team))3
When
len(team)is executed,
Python internally calls
team.__len__()Write a Python program to overload the + operator.
class Number:
def __init__(self, value):
self.value = value
def __add__(self, other):
return Number(self.value + other.value)
num1 = Number(10)
num2 = Number(20)
result = num1 + num2
print(result.value)30
Python converts
num1 + num2into
num1.__add__(num2)This is called Operator Overloading.
class Number:
def __init__(self, value):
self.value = value
def __sub__(self, other):
return Number(self.value - other.value)
num1 = Number(50)
num2 = Number(20)
result = num1 - num2
print(result.value)30
Python internally calls
num1.__sub__(num2)when the - operator is used.
class Student:
def __init__(self, marks):
self.marks = marks
def __eq__(self, other):
return self.marks == other.marks
student1 = Student(90)
student2 = Student(90)
print(student1 == student2)True
The == operator internally invokes
__eq__()class Student:
def __init__(self, marks):
self.marks = marks
def __lt__(self, other):
return self.marks < other.marks
student1 = Student(80)
student2 = Student(90)
print(student1 < student2)True
The < operator calls
__lt__()class Student:
def __init__(self, marks):
self.marks = marks
def __gt__(self, other):
return self.marks > other.marks
student1 = Student(95)
student2 = Student(90)
print(student1 > student2)True
The > operator internally calls
__gt__()class Team:
def __init__(self):
self.players = ["Rahul", "Priya", "Kiran"]
def __contains__(self, player):
return player in self.players
team = Team()
print("Rahul" in team)True
The in operator internally calls
__contains__()class Numbers:
def __init__(self):
self.data = [10, 20, 30, 40]
def __getitem__(self, index):
return self.data[index]
numbers = Numbers()
print(numbers[2])30
Indexing
numbers[2]internally calls
numbers.__getitem__(2)class Numbers:
def __init__(self):
self.data = [10, 20, 30]
def __setitem__(self, index, value):
self.data[index] = value
numbers = Numbers()
numbers[1] = 100
print(numbers.data)[10, 100, 30]
Assignment using an index internally invokes
__setitem__()class Greeting:
def __call__(self):
print("Hello, Welcome!")
greet = Greeting()
greet()Hello, Welcome!
Objects become callable when the
__call__()method is implemented.
class Student:
def __str__(self):
return "Readable Output"
def __repr__(self):
return "Official Representation"
student = Student()
print(student)
print(repr(student))Readable Output
Official Representation
__str__()→ User-friendly representation__repr__()→ Developer/debug representation
class Money:
def __init__(self, amount):
self.amount = amount
def __add__(self, other):
return Money(self.amount + other.amount)
def __str__(self):
return f"₹{self.amount}"
wallet1 = Money(500)
wallet2 = Money(1500)
print(wallet1 + wallet2)₹2000
Two Money objects are added using the overloaded + operator.
Python internally executes
wallet1.__add__(wallet2)and then displays the result using
__str__()Object Created
↓
Operator Used
↓
Python Finds Matching Magic Method
↓
Magic Method Executes
↓
Result Returned
Money Object
│
▼
+---------------------------+
amount
↓
500
---------------------------
__add__()
__str__()
+---------------------------+
- Customizes object behavior.
- Enables Operator Overloading.
- Integrates with Python built-in functions.
- Improves code readability.
- Makes user-defined classes behave like built-in types.
- Override only the Magic Methods your class needs.
- Keep Magic Methods simple and predictable.
- Ensure overloaded operators behave naturally.
- Implement both
__str__()and__repr__()when appropriate. - Return the correct data types from Magic Methods.
Returning a non-string from __str__().
❌ Incorrect
def __str__(self):
return 100__str__() must return a string.
Assuming Magic Methods are called directly.
Normally, use operators or built-in functions instead of calling methods like __add__() manually.
Overloading operators with unexpected behavior.
For example, + should generally represent addition or combination, not an unrelated action.
Confusing __str__() and __repr__().
__str__() is for end users.
__repr__() is for developers and debugging.
Magic Methods are predefined special methods surrounded by double underscores that Python automatically invokes for built-in operations.
Because they begin and end with double underscores (__), which stands for Double Under.
It initializes an object immediately after it is created.
__str__()provides a readable string for users.__repr__()provides an unambiguous representation for developers.
Operator Overloading allows built-in operators such as +, -, and == to work with user-defined objects.
__add__().
__len__().
__call__().
__getitem__().
No.
Only Python's predefined special method names have special behavior.
- Implement
__str__()in a Student class. - Overload the
+operator using__add__(). - Implement
__len__()for a custom collection. - Create a callable object using
__call__(). - Implement
__getitem__()and__setitem__()for a custom list class.
- Magic Methods are also called Dunder Methods.
- Python automatically invokes them.
__init__()initializes objects.__str__()returns a readable string.__repr__()returns a developer representation.__len__()supportslen().__add__()overloads+.__call__()makes objects callable.__getitem__()supports indexing.__contains__()supports theinoperator.
In this chapter, we learned:
- Magic Methods
- Dunder Methods
__init__()__str__()__repr__()__len__()__add__()__sub__()__eq__()__lt__()__gt__()__contains__()__getitem__()__setitem__()__call__()- Operator Overloading
- Practical Programs
- Best Practices
- Common Mistakes
- Interview Questions
- Practice Programs
- Quick Revision