Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
📘 Lesson  ·  Lesson 52

Magic (Dunder) Methods in Python

In this lesson: Customise Python classes with dunder methods — __init__, __str__, __repr__, __len__, __add__ — with output. In Hindi & English.

What are magic methods

Magic methods (also called dunder methods, for "double underscore") are special methods with names like __str__ and __add__. You never call them directly — Python calls them automatically when you print an object, add two objects, check their length, and more. They let your class behave like a built-in type.

💡 Dunder = "double underscore". These methods are triggered by Python behind the scenes.

__str__ — printable text

class Book:
    def __init__(self, title):
        self.title = title
    def __str__(self):
        return "Book: " + self.title

b = Book("Python 101")
print(b)
Book: Python 101

__str__ decides what print(b) shows. Without it, printing an object gives an unhelpful memory address; with it, you get clean, readable output.

__len__ — length

class Team:
    def __init__(self, members):
        self.members = members
    def __len__(self):
        return len(self.members)

t = Team(["Aman", "Diya", "Kabir"])
print(len(t))
3

__len__ is called when you use len(t) on your object. Here it returns how many members the team has, so len() works naturally.

__add__ — the + operator

class Money:
    def __init__(self, amount):
        self.amount = amount
    def __add__(self, other):
        return Money(self.amount + other.amount)

total = Money(100) + Money(50)
print(total.amount)
150

__add__ defines what + means for your class — this is called operator overloading. Now Money(100) + Money(50) makes sense and returns a new Money of 150.

__eq__ — comparison

class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y
    def __eq__(self, other):
        return self.x == other.x and self.y == other.y

print(Point(1, 2) == Point(1, 2))
True

__eq__ defines what == means. By default two objects are equal only if they are the exact same object; here we compare by value, so two points with the same coordinates are equal.

Common mistakes

  • Calling dunder methods directly. Write print(b), not b.__str__() — Python calls them for you.
  • __str__ not returning a string. It must return text, not print it.
  • Wrong spelling. Two underscores each side: __add__, not _add_.
  • Forgetting other. Methods like __add__ and __eq__ take a second object to work with.

Summary

  • Magic (dunder) methods have double underscores and are called automatically.
  • __str__ controls what print() shows.
  • __len__ makes len() work on your object.
  • __add__ defines the + operator (operator overloading).
  • __eq__ defines how == compares your objects.

Next, revise classes with self and __init__, or extend them with inheritance and polymorphism.

Frequently Asked Questions

What are magic methods (dunder methods) in Python?
Magic methods are special methods whose names start and end with double underscores, like __init__ or __str__. You do not call them directly — Python calls them automatically for actions like printing, adding or comparing objects.
Why are they called dunder methods?
"Dunder" is short for "double underscore". Since these methods are written with two underscores on each side (__str__), Python programmers call them dunder methods.
What does __str__ do?
__str__ decides what print(object) shows. Without it, printing an object shows something unhelpful like a memory address. With it, you control a clean, readable text form.
How do I make + work on my own objects?
Define __add__(self, other) in your class. Then Python calls it when you write obj1 + obj2. This is called operator overloading — giving operators meaning for your class.
What does __eq__ control?
__eq__(self, other) defines what == means for your objects. By default, == checks if they are the same object; with __eq__ you can compare by their values instead.
← Back to Python Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.
Next topicself and __init__ Your progress: 52 / 66 (79%) · Lesson 53 / 66 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free