MyInternships.in

Python OOP

Python Dunder Methods

Dunder methods (short for double underscore) are special methods like __init__ and __str__ that let your custom classes work with Python's built-in syntax, such as print(), len() and +.


Printing Objects: __str__ and __repr__

By default, printing an object shows an unhelpful memory address. Defining __str__ controls what print() and str() display, while __repr__ controls the developer-facing representation, useful in debugging.

Customising how an object prints
Python
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __str__(self):
        return f"Point({self.x}, {self.y})"

p = Point(2, 3)
print(p)
Output
Output
Point(2, 3)

Operator Overloading

Dunder methods also let you redefine how operators like +, ==, and functions like len() behave for your own classes. This is called operator overloading.

Adding, comparing and measuring Points
Python
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __add__(self, other):
        return Point(self.x + other.x, self.y + other.y)

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

    def __str__(self):
        return f"Point({self.x}, {self.y})"

p1 = Point(1, 2)
p2 = Point(3, 4)
print(p1 + p2)
print(p1 == Point(1, 2))
Output
Output
Point(4, 6)
True
Dunder MethodTriggered ByPurpose
__str__print(obj), str(obj)friendly display string
__repr__repr(obj), console echounambiguous debug string
__len__len(obj)define object length
__eq__obj1 == obj2define equality logic
__add__obj1 + obj2define + behaviour
💡

You do not need to memorise every dunder method — learn __init__, __str__ and __eq__ first, then add __add__, __len__ and others as your classes need them.

Related Python Topics

Keep learning with these closely related lessons.

Ready to use your Python skills?

Find Python, data science and software internships and fresher jobs across India.

Browse Python Internships