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.
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)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.
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))Point(4, 6)
True| Dunder Method | Triggered By | Purpose |
|---|---|---|
| __str__ | print(obj), str(obj) | friendly display string |
| __repr__ | repr(obj), console echo | unambiguous debug string |
| __len__ | len(obj) | define object length |
| __eq__ | obj1 == obj2 | define equality logic |
| __add__ | obj1 + obj2 | define + 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.
