Py Dunder Methods — Free Python Tutorial

Learn Py Dunder Methods in Python with a free, beginner-friendly tutorial, examples and practice for Indian students on Syllab.in.

Py Dunder Methods — Free Python Tutorial

Learn Py Dunder Methods in Python with a free, beginner-friendly tutorial, examples and practice for Indian students on Syllab.in.

✓ 100% Free ✓ No Login Needed ✓ NCERT / CBSE Aligned ✓ Download as PDF

TL;DR: Learn Py Dunder Methods in Python with a free, beginner-friendly tutorial, examples and practice for Indian students on Syllab.in.

Written & reviewed by the Syllab.in Academic Team (CBSE/NCERT subject experts) · Updated

🤖 Stuck on any question? Ask Syllab's free AI Tutor for a step-by-step explanation — instant, unlimited, no login.

Py Dunder Methods in Python

Dunder methods (double underscore methods) let you define how your objects behave with Python operators and built-in functions. They are the heart of Python's data model.

__str__ and __repr__: control how your object is printed. __str__ is human-friendly, __repr__ is developer-friendly (for debugging).

__len__, __getitem__, __setitem__: make your object behave like a list or dict. __iter__ and __next__ make it iterable.

__add__, __sub__, __mul__: define arithmetic. __eq__, __lt__, __gt__: define comparisons. This is called operator overloading.

Py Dunder Methods — Syntax

class MyClass:
    def __init__(self, value):
        self.value = value
    def __str__(self):      # print(obj) → human readable
        return f"MyClass({self.value})"
    def __repr__(self):     # repr(obj) → developer view
        return f"MyClass(value={self.value!r})"
    def __len__(self):      # len(obj)
        return self.value
    def __add__(self, other):  # obj1 + obj2
        return MyClass(self.value + other.value)
    def __eq__(self, other):   # obj1 == obj2
        return self.value == other.value

Learn Py Dunder Methods step by step with Syllab's free interactive Python tutorial — runnable code examples, practice exercises and instant AI feedback, all free with no signup. Explore the full Python course →