Dunder Methods
Special __double underscore__ methods customise how objects behave.
Syntax
def __str__(self):
return ...Dunder (double-underscore) methods let your objects work with Python's built-in operations. Python calls them for you at the right moment.
Useful ones
__str__— the friendly text shown byprint().__repr__— an unambiguous developer representation.__len__— makeslen(obj)work.__eq__— defines what==means.
Example
class Money:
def __init__(self, amount):
self.amount = amount
def __str__(self):
return f'${self.amount:.2f}'
wallet = Money(9.5)
print(wallet)
# Output:
# $9.50When to use it
- A Money class implements __add__ so two Money objects can be summed with the + operator.
- A Grid class implements __len__ to return its cell count so len(grid) works naturally.
- A Config class implements __repr__ to display a readable summary when printed in the REPL.
More examples
__str__ and __repr__
Implements __repr__ for unambiguous debug output and __str__ for a human-friendly display.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return f'Point({self.x}, {self.y})'
def __str__(self):
return f'({self.x}, {self.y})'
p = Point(3, 4)
print(repr(p)) # Point(3, 4)
print(p) # (3, 4)__len__ and __contains__
Enables len(bag) via __len__ and the 'in' operator via __contains__.
class Bag:
def __init__(self, items):
self.items = list(items)
def __len__(self):
return len(self.items)
def __contains__(self, item):
return item in self.items
bag = Bag(['apple', 'banana', 'cherry'])
print(len(bag)) # 3
print('banana' in bag) # True__add__ operator overloading
Overloads the + operator with __add__ so two Vector objects can be added naturally.
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __repr__(self):
return f'Vector({self.x}, {self.y})'
v1 = Vector(1, 2)
v2 = Vector(3, 4)
print(v1 + v2) # Vector(4, 6)
Discussion