__format__ — Easy Examples
Called by format() and f-strings for custom formatting
Implementing __format__
Basic implementation of __format__ in a class.
python
class Example: def __format__(self): return "Example __format__" obj = Example() print(obj)
__format__ called by format() and f-strings for custom formatting. Implementing it lets you customize how Python interacts with your objects.
__format__ in action
Seeing __format__ called by Python's built-in operations.
python
# How Python calls __format__ automatically class Demo: def __init__(self, value): self.value = value def __format__(self): print(f"__format__ was called!") return self d = Demo(42) # This triggers __format__: print(d)
Python automatically calls __format__ when you use the corresponding operator or function on your object.
Want to try these examples interactively?
Open Easy Playground