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.
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
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):
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 →