Lesson 26 / 47
Dunder Methods
Double-underscore methods let your objects work with built-in operators and functions.
__str__ and __repr__
__str__ controls print(obj) / str(obj); __repr__ is the developer-facing representation seen in the REPL.
class Point:
def __init__(self, x, y):
self.x, self.y = x, y
def __str__(self):
return f"({self.x}, {self.y})"
def __repr__(self):
return f"Point(x={self.x}, y={self.y})"
p = Point(2, 3)
print(p) # (2, 3) -- uses __str__
print([p]) # [Point(x=2, y=3)] -- uses __repr____eq__
__eq__ defines what == means for your objects — without it, two "equal-looking" objects compare unequal by identity.
class Point:
def __init__(self, x, y):
self.x, self.y = x, y
def __eq__(self, other):
return self.x == other.x and self.y == other.y
print(Point(1, 2) == Point(1, 2)) # True