🐍 Python - Custom Class Formatting
Updated at 2018-06-09 14:41
You can add __format__ to improve formatting options of your classes.
from typing import NamedTuple
class Vector(NamedTuple):
x: int
y: int
def __format__(self, spec: str = '') -> str:
fmt_x = format(self.x, spec)
fmt_y = format(self.y, spec)
return f'({fmt_x}, {fmt_y})'
v1 = Vector(1, 2)
assert format(v1) == '(1, 2)'
assert format(v1, '.2f') == '(1.00, 2.00)'
assert f'{v1:.2f}' == '(1.00, 2.00)'
Source
- Python Tricks The Book, Dan Bader
- Fluent Python, Luciano Ramalho