Intellipaat

Intellipaat

Explore Online Courses Free Courses Hire from us Become an Instructor Reviews
All Courses
  • Articles
  • Tutorials
  • Interview Questions
Home > Blog > Tutorials > Python Tutorial For Beginners > Magic Methods In Python

Magic Methods In Python

By Lithin Reddy | Last updated on October 14, 2025 | 19056 Views
Share this article
Previous
Next
Tutorial Playlist
    • Python Tutorial For Beginners
    • Python Itertools
    • How to use Python numpy.where() Method?
    • Python Break & Continue statements
    • What Does “elif” Mean in Python?
    • Magic Methods In Python
    • Python Fundamentals - Learn Python Basics
    • Introduction and History of Python
    • What is Python Programming Language?
    • Python Version History
    • Top 10 Python Frameworks
    • Python Download - How To Install Python [Easy Steps]
    • Python Syntax: A Guide To Writing Basic Python Code
    • What are comments in python
    • Python Input and Output Commands
    • Python Data Types: Complete Guide with Examples (2026)
    • Python Variables
    • Python Numbers - Learn How to Create Prime Numbers, Perfect Numbers, and Reverse Numbers in Python
    • Strings in Python
    • Python Lists - A Complete Guide (With Syntax and Examples)
    • Tuples in Python
    • Python Set - The Basics
    • Dictionaries in Python - From Key-Value Pairs to Advanced Methods
    • Python Operators
    • Python Modules, Regular Expressions & Python Frameworks
    • Type Conversion in Python
    • Python If Else Statements - Conditional Statements with Examples
    • Python While Loop
    • Python for Loops - A Step-by-Step Guide
    • Python Function - Example & Syntax
    • Python Lambda Functions - A Beginner's Guide
    • Python Built-in Functions
    • Python Arrays - The Complete Guide
    • Python Classes and Objects
    • Introduction to Python Modules
    • Python Datetime - A Guide to Work With Dates and Times in Python
    • Python JSON - Parsing, Creating, and Working with JSON Data
    • What is Regular Expression in Python
    • How to Install Pip in Python
    • File Handling in Python
    • Exception Handling in Python with Examples
    • Enumerate() in Python - A Detailed Explanation
    • Python Queue Tutorial: Queue Module, Deque & Priority Queue (2026)
    • Numpy - Features, Installation and Examples
    • SciPy in Python Tutorial
    • Python Scikit-Learn
    • Python Pandas - Features and Use Cases (With Examples)
    • Introduction to Matplotlib in Python
    • Python Cheat Sheet - Basics to Regex, Syntax, and Data Types [UPDATED]
    • Data Structures with Python Cheat Sheet
    • NumPy Cheat Sheet
    • Scikit-Learn Cheat Sheet: Python Machine Learning
    • Pandas Cheat Sheet
    • List Comprehension in Python
    • Web Scraping with Python - A Step-by-Step Tutorial
    • Python Tutorial For Beginners
    • Python Itertools
    • How to use Python numpy.where() Method?
    • Python Break & Continue statements
    • What Does “elif” Mean in Python?
    • Magic Methods In Python
    • Python Fundamentals - Learn Python Basics
    • Introduction and History of Python
    • What is Python Programming Language?
    • Python Version History
    • Top 10 Python Frameworks
    • Python Download - How To Install Python [Easy Steps]
    • Python Syntax: A Guide To Writing Basic Python Code
    • What are comments in python
    • Python Input and Output Commands
    • Python Data Types: Complete Guide with Examples (2026)
    • Python Variables
    • Python Numbers - Learn How to Create Prime Numbers, Perfect Numbers, and Reverse Numbers in Python
    • Strings in Python
    • Python Lists - A Complete Guide (With Syntax and Examples)
    • Tuples in Python
    • Python Set - The Basics
    • Dictionaries in Python - From Key-Value Pairs to Advanced Methods
    • Python Operators
    • Python Modules, Regular Expressions & Python Frameworks
    • Type Conversion in Python
    • Python If Else Statements - Conditional Statements with Examples
    • Python While Loop
    • Python for Loops - A Step-by-Step Guide
    • Python Function - Example & Syntax
    • Python Lambda Functions - A Beginner's Guide
    • Python Built-in Functions
    • Python Arrays - The Complete Guide
    • Python Classes and Objects
    • Introduction to Python Modules
    • Python Datetime - A Guide to Work With Dates and Times in Python
    • Python JSON - Parsing, Creating, and Working with JSON Data
    • What is Regular Expression in Python
    • How to Install Pip in Python
    • File Handling in Python
    • Exception Handling in Python with Examples
    • Enumerate() in Python - A Detailed Explanation
    • Python Queue Tutorial: Queue Module, Deque & Priority Queue (2026)
    • Numpy - Features, Installation and Examples
    • SciPy in Python Tutorial
    • Python Scikit-Learn
    • Python Pandas - Features and Use Cases (With Examples)
    • Introduction to Matplotlib in Python
    • Python Cheat Sheet - Basics to Regex, Syntax, and Data Types [UPDATED]
    • Data Structures with Python Cheat Sheet
    • NumPy Cheat Sheet
    • Scikit-Learn Cheat Sheet: Python Machine Learning
    • Pandas Cheat Sheet
    • List Comprehension in Python
    • Web Scraping with Python - A Step-by-Step Tutorial
`; ip_get_section_iq.innerHTML = sidebarhtml_desk; playlistmobile.innerHTML = sidebarhtml_desk; var ip_iq_scriptToRemove = document.getElementById('ip-blog-iq-script-removal'); if (ip_iq_scriptToRemove) { ip_iq_scriptToRemove.remove(); } var activeSubmenuItems = document.querySelectorAll('.tutorial_list_submenu li.active'); activeSubmenuItems.forEach(function(activeItem) { var rootParentLi = activeItem.closest('.maincata'); if (rootParentLi) { rootParentLi.classList.add('opentutorialsubmenu'); } }); var ip_blog_tutorialListMenu = document.querySelector('.tutorial_list_menu'); if(ip_blog_tutorialListMenu){ var ip_blo_activeItem = ip_blog_tutorialListMenu.querySelector('li.active'); var lastlink = ''; var nextlink = ''; var total = 0; jQuery('#TutorialLeftArea .maincata ul').children('li').each(function(indexx) { total = indexx; }); jQuery('#TutorialLeftArea .maincata ul').children('li').each(function(i) { var isActive = jQuery(this).hasClass('active'); if(isActive){ if(i !== 0){ var lastIndexedElement = jQuery('#TutorialLeftArea .maincata ul').children('li').eq(i - 1); lastlink = lastIndexedElement.children('a').attr('href'); }else{ lastlink = ''; } if(total > i){ var nextIndexedElement = jQuery('#TutorialLeftArea .maincata ul').children('li').eq(i + 1); nextlink = nextIndexedElement.children('a').attr('href'); }else{ nextlink = ''; } return false; } }); var ip_blog_prevBlog = document.querySelector('.prev-blog a'); var ip_blog_nextBlog = document.querySelector('.next-blog a'); if (lastlink !== '' && typeof lastlink !== 'undefined') { ip_blog_prevBlog.setAttribute('href', lastlink); }else { if(ip_blog_prevBlog){ ip_blog_prevBlog.style.display = 'none'; } } if (nextlink !== '' && typeof nextlink !== 'undefined') { ip_blog_nextBlog.setAttribute('href', nextlink); }else { if(ip_blog_nextBlog){ ip_blog_nextBlog.style.display = 'none'; } } } function ip_blog_setActiveLink() { var divElements = document.querySelectorAll('div[id]'); var links = document.querySelectorAll('.interview-question-bookmark-list-alt li a'); var activeLink = null; divElements.forEach(function(div) { if (ip_blog_isInViewportThreshold(div, 50)) { var ip_blog_divId = div.getAttribute('id'); links.forEach(function(link) { if (link.getAttribute('href') === '#' + ip_blog_divId) { activeLink = link; } }); } }); links.forEach(function(link) { link.classList.remove('active'); }); if (activeLink) { activeLink.classList.add('active'); } } function ip_blog_isInViewportThreshold(element, threshold) { var rect = element.getBoundingClientRect(); var windowHeight = window.innerHeight || document.documentElement.clientHeight; var topThreshold = rect.top - threshold; var bottomThreshold = rect.bottom + threshold; return topThreshold <= windowHeight && bottomThreshold >= 0; } window.addEventListener('scroll', ip_blog_setActiveLink); window.addEventListener('load', ip_blog_setActiveLink); }); function ip_blg_findClosestAnchor(element) { while (element) { if (element.tagName === 'A') { return element; } element = element.parentNode; } return null; } function ip_bl_v_scrollToDiv(event_pb, offset) { event_pb.preventDefault(); const ip_bl_linkElement = ip_blg_findClosestAnchor(event_pb.target); if (ip_bl_linkElement) { const it_bl_hashValue = ip_bl_linkElement.getAttribute('href').substring(1); const it_blg_vf_targetElement = document.getElementById(it_bl_hashValue); if (it_blg_vf_targetElement) { jQuery('html, body').animate({ scrollTop: jQuery('#' + it_bl_hashValue).offset().top - offset }, 1000); } } } document.addEventListener('DOMContentLoaded', function() { let it_bl_offset = 0; const ip_blo_vi_anchorLinks = document.querySelectorAll('a[href^="#"]'); ip_blo_vi_anchorLinks.forEach(function(linkip_bg) { linkip_bg.addEventListener('click', function(event_pb) { setTimeout(function() { console.log('Offset passed during click: ' + it_bl_offset); ip_bl_v_scrollToDiv(event_pb, it_bl_offset); }, 0); }); }); });
See More

Python is a versatile language that has multiple features to perform a various array of tasks from basic programming to performing complex machine learning tasks. Now if we talk about the magic method, this is also one of the powerful tools to customize the class behavior in Python. It is also called the dunder (double underscore) method, as these are the special methods that are surrounded by double underscores(e.g.,__init__,__str__) that enable you to define how your custom classes work when certain operations are performed on them. Let us dive into the blog to understand in detail about these magic methods and what they can do.

Table of Contents

  • What is a  Magic Method in Python?
  • Controlling the Object Creation Process
  • Representing Objects as Strings
  • Supporting Operator Overloading in Custom Classes

What is a Magic Method in Python?

In the beginning, we learned that the magic method in Python is the special method that is surrounded by double underscores. These methods are the predefined methods that allow the objects to have some specific behaviors. These are mostly used to perform an operation called overloading as well as arithmetic operations (addition, subtraction), comparison operations, string representation, etc. Magic methods are called implicitly by Python and thus provide a way to integrate custom objects smoothly into the Python environment.

Controlling the Object Creation Process

  1. Object initialization: __init__

The __init__ method is used to initialize the object’s attributes when an instance of the class is created.

Now let us understand the same thing with an example:

Python
Code Copied!

#output:
Ashna

The __init__ method assigns the values “Ashna” and “Data Science” to the name and course, respectively. When the student object is created, these attributes are initialized automatically.

  1. Creating Objects: __new__():

The __new__() is a special method that is used for creating an instance of a class. It is mostly called before the __init__() method and is mostly used when you want to control the creation process of an object, like when you are dealing with immutable objects such as tuples and strings.

Now let us take an example:

Python
Code Copied!

Shape Your Career in Data Science
Grow with Our Data Science Training
Explore Program
quiz-icon

Representing Objects as Strings

  1. __str__():

It is used to define a user-friendly representation of an object. It gives you human-readable output when you are printing the object. Python uses this method internally when you are calling the str() function using an instance of the class, which is passed as an argument.

Let us take an example of the same:

Python
Code Copied!
  1. __repr__():

It is used to define a string representation of an object. If you print an object or inspect it in a Python interactive shell, this method is used to decide the output displayed. This makes it easier to debug by giving meaningful results about an object.

For example:

class Student:
def __init__(self, course, marks):
self.course = course
self.marks = marks
def __repr__(self):
return f"Student(course='{self.course}', marks={self.marks})"

# Example usage

student = Student("Data Science", 80)
print(student)

Output:

Student(course='Data Science', marks=80)

Supporting Operator Overloading in Custom Classes

Arithmetic Operators

Magic method for arithmetic operators lets you understand how objects in your class answer to mathematical operations. Below is a list of operators along with the magic method and an example of how you can use it.

Operator Magic Method
+ __add__()
– __sub__()
* __mul__()
/ __truediv__()
// __floordiv__()
% __mov__()
** __pow__()

Let us under by taking some examples:

Python
Code Copied!

The __add__() method allows the + operator to add two Vector objects. It returns a new Vector with the summed x and y values.
Learn Python for Free and get certified!
Kickstart Your Programming Journey with Our Free Python Course.
Explore Program
quiz-icon

Comparison Operator Methods

This method gives results about how the objects are compared:

Operator Magic Method
== __eq__(self, other)
!= __ne__(self, other)
< __lt__(self, other)
<= __le__(self, other)
> __gt__(self, other)
>= __ge__(self, other)

Examples:

class Student:
def __init__(self, course, marks):
self.course = course
self.marks = marks
def __lt__(self, other):
return self.marks < other.marks

# Usage

student1 = Student("Data Science", 80)
student2 = Student("Discrete Mathematics", 90)
print(student1 < student2)

Output:

True

Get 100% Hike!

Master Most in Demand Skills Now!

Conclusion

Magic methods in Python enable you to add custom behavior to your classes, making objects behave like built-in types by overriding methods such as __str__, __len__, or __add__. In Python, magic methods allow you to define how objects interact with operators, customize string representations, and make containers. Using these methods adds a “magic” touch to your code, enabling intuitive, Pythonic design, and once mastered, their proper use is all practice. If you want to learn more about Python, you can refer to our Python Course.

Below materials introduce essential Python basics, including syntax, concepts, and operators for beginners.

Elif in Python – Delve into the use of the elif statement in Python, supported by practical examples.

Break and Continue – Discover how to break and continue work in Python, illustrated with helpful examples.

Python Reserved Words – Covers Python reserved words and demonstrates their use with examples.

Python Interactive Mode Chevron – Overview of Python’s interactive mode and chevron prompt with real-world examples.

Global Variable in Function – Explore how global variables behave inside functions in Python, with detailed examples.

Python Yield Keyword – Understand the yield keyword in Python and how it functions, supported by sample code.

Python Tuple – Take a closer look at tuples in Python, with explanations and practical examples.

Set Attribute Error – Learn what causes a setattr error in Python and how to handle it, using examples.

2D Array Input – See how to take input for a 2D array in Python through easy-to-follow examples.

About the Author

Lithin Reddy
Lithin Reddy
Data Scientist | Technical Research Analyst - Analytics & Business Intelligence

Lithin Reddy is a Data Scientist and Technical Research Analyst with around 1.5 years of experience, specializing in Python, SQL, system design, and Power BI. Known for building robust, well-structured solutions and contributing clear, practical insights that address real-world development challenges.

Recommended Videos
Python Interview Questions And Answers
Python Interview Questions And Answers
Numpy Interview Questions For Freshers
Numpy Interview Questions For Freshers
Pandas Coding Interview Questions
Pandas Coding Interview Questions
OOPS Interview Questions and Answers
OOPS Interview Questions and Answers
Python Pandas Tutorial
Python Pandas Tutorial
Recommended Programs
Python Course
Python Course
5 (218118)
Free Python Certification Course Online
Free Python Certification Course Online
5 (53455)
Python Data Science Course
Python Data Science Course
5 (76533)
Software Development Engineering Course
Software Development Engineering Course
5 (23421)

Course Preview

Expert-Led No.1

Magic Methods In Python

Intellipaat

facebook twitter linkedin youtube insta telegram

Intellipaat

facebook twitter linkedin youtube insta telegram

Get Our App Now!

Intellipaat android app Intellipaat android app

Get Our App Now!

Intellipaat android app Intellipaat android app

Courses

  • Data Scientist Course
  • Machine Learning Course
  • Python Course
  • Devops Training
  • Business Analyst Certification
  • Cyber Security Courses
  • Business Analytics Training
  • Investment Banking Course
  • SQL Course
  • AWS DevOps Course
  • Full Stack Developer Course
  • Product Management Course

Courses

  • AWS Solutions Architect
  • UI UX Design Course
  • Salesforce Training
  • Selenium Training
  • Artificial Intelligence Course
  • Ethical Hacking Course
  • Azure Administrator Certification
  • Cyber Security Course
  • Digital Marketing Course
  • Electric Vehicle Course
  • Azure DevOps Course
  • Web Development Courses

Tutorials

  • Python Tutorial
  • AWS Tutorial
  • Devops Tutorial
  • Java Tutorial
  • Node Js Tutorial
  • Cyber Security Tutorial
  • Salesforce Tutorial
  • Azure Tutorial
  • Ethical Hacking Tutorial
  • Data Science Tutorial
  • Cloud Computing Courses
  • Python Data Science Course

Interview Questions

  • Python Interview Questions
  • AWS Interview Questions
  • Data Science Interview Questions
  • Devops Interview Questions
  • Salesforce Interview Questions
  • Java Interview Questions
  • SQL Interview Questions
  • React Interview Questions
  • Node Js Interview Questions
  • Digital Marketing Interview Questions

Browse By Domains

Data Science Salesforce Courses Cloud Computing Courses AI & Machine Learning Courses Project Management Courses Cyber Security and Ethical Hacking Courses Web Development Courses Job Oriented Courses Degree Courses Marketing CRM Courses Software Development Courses Doctorate Programs Undergraduate Courses Banking and Finance Courses Product Design Courses Electric and Hybrid Vehicle Courses Leadership & Management Courses Management Courses Generative AI Courses Design Thinking Courses Microsoft Certification Courses

Top Tutorials

Machine Learning Tutorial Power BI Tutorial SQL Tutorial Artificial Intelligence Tutorial Digital Marketing Tutorial Data Analytics Tutorial UI/UX Tutorial

Top Articles

Cloud Computing Data Science Machine Learning What is AWS Digital Marketing Cyber Security Salesforce Artificial Intelligence

Top Interview Questions

Selenium Interview Questions Azure Interview Questions Machine Learning Interview Questions Cyber Security Interview Questions Business Analyst Interview Questions and Answers C Interview Questions Data Analyst Interview Questions Software Engineering Interview Questions

© Copyright 2011 - 2026 Intellipaat Software Solutions Pvt. Ltd.
Media
Contact Us
Tutorials
Interview Questions

Address: 6th Floor, Primeco Towers, Arekere Gate Junction, Bannerghatta Main Road, Bengaluru, Karnataka 560076, India.

Disclaimer: The certification names are the trademarks of their respective owners.

INTPL_2026-05-22