Hackforge Academy

Category: python

Dunder Methods in python

Published on 14 Feb 2026

Explanation

What are Dunder Methods? Dunder = Double UNDERscore They look like: __init__ __str__ __add__ __len__ 1.These are special methods 2.Python calls automatically in certain situations. 3.Should n't call them directly 4.Python calls behind the screen

Code:


Explanation


Why Dunder Methods Matter They let your custom objects behave like built-in types.

Code:

Example:

a + b
len(x)
print(obj)
obj == other
All of these use dunder methods internally.

Explanation

__init__ – Object Creation Called when an object is created.

Code:

class User:
    def __init__(self, name):
        self.name = name

u = User("hackforge")

Explanation

__str__ vs __repr__ __str__ β†’ human-friendly __repr__ β†’ developer-friendly

Code:

class Car:
    def __init__(self, brand):
        self.brand = brand
    def __str__(self):
        return f"Car brand: {self.brand}"
    def __repr__(self):
        return f"Car('{self.brand}')"

car = Car("Tesla")
print(car)

Explanation

__len__ Controls behavior of len().

Code:

class Playlist:
    def __init__(self, songs):
        self.songs = songs

    def __len__(self):
        return len(self.songs)

p = Playlist(["song1", "song2", "song3"])
print(len(p))  # 3

Explanation


Dunder methods are hooks in Python 1.Makes code clean, readable, Pythonic 2.Used heavily in frameworks & libraries

Code:


πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community