Dunder Methods (Magic Methods) in Python: A Complete Beginner-to-Advanced Guide
Python is known for its clean syntax and powerful object-oriented programming features. One of the most powerful yet often misunderstood concepts is Dunder Methods, also called Magic Methods.
If you've ever wondered how Python knows what to do when you write +, ==, len(), or print() on your custom objects, the answer lies in dunder methods.
In this guide, we'll explore what dunder methods are, why they matter, and how you can use them to build more Pythonic applications.
What Are Dunder Methods?
Dunder stands for Double UNDERscore.
Dunder methods are special methods in Python whose names begin and end with two underscores.
Examples include:
__init__
__str__
__repr__
__len__
__add__
__eq__
__getitem__
These methods are also known as Magic Methods because Python automatically invokes them when certain operations are performed on objects.
Why Are Dunder Methods Important?
Dunder methods allow your custom classes to behave like Python's built-in data types.
For example:
+calls__add__()==calls__eq__()len()calls__len__()print()calls__str__()
Without dunder methods, your custom objects would not integrate naturally with Python's built-in functions and operators.
Example 1: init()
The __init__() method is the constructor of a class.
class Student:
def __init__(self, name):
self.name = name
student = Student("Vinod")
print(student.name)
Output
Vinod
Python automatically executes __init__() when an object is created.
Example 2: str()
The __str__() method defines how an object should appear when printed.
class Student:
def __init__(self, name):
self.name = name
def __str__(self):
return f"Student Name: {self.name}"
student = Student("Vinod")
print(student)
Output:
Student Name: Vinod
Without __str__(), Python would display the object's memory address.
Example 3: repr()
__repr__() provides an official string representation of an object.
class Student:
def __repr__(self):
return "Student('Vinod')"
It is mainly used for debugging.
Example 4: len()
You can customize the behavior of the len() function.
class Team:
def __len__(self):
return 5
team = Team()
print(len(team))
Output
5
Example 5: add()
Customize the + operator.
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
Example 6: eq()
Control how objects are compared using ==.
class Employee:
def __init__(self, salary):
self.salary = salary
def __eq__(self, other):
return self.salary == other.salary
emp1 = Employee(50000)
emp2 = Employee(50000)
print(emp1 == emp2)
Output
True
Example 7: getitem()
Allows indexing.
class Numbers:
def __init__(self):
self.data = [10,20,30]
def __getitem__(self,index):
return self.data[index]
nums = Numbers()
print(nums[1])
Output
20
Example 8: setitem()
Customize assignment using indexes.
class Numbers:
def __init__(self):
self.data=[10,20,30]
def __setitem__(self,index,value):
self.data[index]=value
nums=Numbers()
nums[1]=200
print(nums.data)
Output
[10, 200, 30]
Example 9: iter() and next()
These methods make your class iterable.
class Counter:
def __init__(self):
self.num=1
def __iter__(self):
return self
def __next__(self):
if self.num<=5:
value=self.num
self.num+=1
return value
raise StopIteration
counter=Counter()
for i in counter:
print(i)
Output
1
2
3
4
5
Commonly Used Dunder Methods
| Dunder Method | Triggered By | Purpose |
|---|---|---|
__init__() | Object creation | Initialize objects |
__str__() | print() | User-friendly representation |
__repr__() | repr() | Developer representation |
__len__() | len() | Return length |
__add__() | + | Addition |
__sub__() | - | Subtraction |
__mul__() | * | Multiplication |
__eq__() | == | Equality comparison |
__lt__() | < | Less than |
__gt__() | > | Greater than |
__getitem__() | obj[index] | Index access |
__setitem__() | obj[index]=value | Item assignment |
__iter__() | for loop | Iterator creation |
__next__() | next() | Return next item |
When Should You Use Dunder Methods?
Use dunder methods when:
Building custom Python classes
Creating reusable libraries
Designing frameworks
Developing APIs
Implementing data structures
Writing production-grade Python applications
They make your classes feel like native Python objects.
Best Practices
Implement only the dunder methods your class genuinely needs.
Keep each method focused on a single responsibility.
Follow Python's data model instead of redefining expected behavior.
Prefer readable, maintainable implementations over clever tricks.
Use
__repr__()for debugging and__str__()for user-friendly output.
Conclusion
Dunder (Magic) Methods are one of Python's most powerful features. They allow your custom classes to interact seamlessly with Python's built-in syntax, operators, and functions.
By mastering methods like __init__(), __str__(), __len__(), __add__(), and __eq__(), you'll write cleaner, more Pythonic, and more maintainable code.
Whether you're preparing for Python interviews or building enterprise applications, understanding dunder methods is an essential skill for every Python developer.
Learn Python and AI with EduArn
Looking to build practical Python and AI skills?
EduArn offers Retail Training and Corporate Training programs designed for students, working professionals, and enterprise teams.
Our training includes:
Python Programming
Data Structures and Algorithms
Object-Oriented Programming
Machine Learning
Deep Learning
Generative AI
Prompt Engineering
LangChain
LangGraph
AI Agents
MLOps
Docker
AWS
Real-world Capstone Projects
Whether you're an individual looking to upskill or an organization planning to train your workforce, Eduarn provides hands-on, instructor-led learning focused on real-world outcomes.
Frequently Asked Questions (FAQs)
1. What are dunder methods in Python?
Dunder methods (short for Double UNDERscore methods) are special methods in Python that begin and end with two underscores, such as __init__() and __str__(). Python automatically calls these methods to define how objects behave with built-in functions and operators.
2. Why are dunder methods called magic methods?
They are called magic methods because Python invokes them automatically behind the scenes when you perform operations like object creation, addition, comparison, iteration, or printing.
3. What is the difference between __str__() and __repr__()?
__str__()returns a user-friendly string representation of an object.__repr__()returns a developer-oriented representation, mainly used for debugging and logging.
4. What is the purpose of the __init__() method?
The __init__() method is the constructor in Python. It is automatically executed when an object is created and is used to initialize the object's attributes.
5. How does __eq__() work in Python?
The __eq__() method defines how two objects are compared using the == operator. It allows you to customize equality comparisons based on your class's attributes.
6. Which Python operators use dunder methods?
Many Python operators internally call dunder methods, including:
+→__add__()-→__sub__()*→__mul__()==→__eq__()<→__lt__()>→__gt__()len()→__len__()print()→__str__()
7. Can I create my own dunder methods?
No. You should only implement the predefined dunder methods provided by Python's data model. Creating custom methods with names like __mymethod__() is discouraged because Python reserves this naming convention for special methods.
8. When should I use dunder methods?
Use dunder methods when developing custom classes that need to work naturally with Python's built-in functions, operators, iteration, indexing, or object comparisons. They are especially useful in object-oriented programming and framework development.
9. Are dunder methods important for Python interviews?
Yes. Questions about __init__(), __str__(), __repr__(), __eq__(), __len__(), and operator overloading are common in Python developer interviews, especially for intermediate and senior roles.
10. Where can I learn Python and dunder methods with hands-on projects?
You can learn Python, Object-Oriented Programming, dunder methods, AI, Machine Learning, LangChain, LangGraph, and Generative AI through Eduarn's Retail Training and Corporate Training programs. The curriculum includes live instructor-led sessions, hands-on projects, and industry-focused learning designed for students, professionals, and enterprise teams.
Keywords: Dunder Methods Python, Magic Methods Python, Python Special Methods, Python OOP, Python Tutorial, Learn Python, Python Training, Corporate Python Training, Retail Python Training, Eduarn Python Course, Python Programming, Python for Beginners.
Which dunder method do you use most often—__init__(), __str__(), or __repr__()?
ReplyDelete