Here’s how we can use it. I’ll fill in a bit of detail so the example is stand-alone, but still ignoring the rest of the functionality of the class:
class Person:
def __init__(self, name, pay):
self.name, self.pay = name, pay
def __format__(self, fmt):
return f'<Person: {self.name}, {self.pay:{fmt}}>'
If we have that, and create an instance like:
worker = Person('Monty', 100.0)
Then it gets used by f-string or .format
formatting:
>>> f'{worker}'
'<Person: Monty, 100.0>'
And we can do fun things like:
>>> f'{worker:>010.2f}'
'<Person: Monty, 0000100.00>'
This does not get used by __str__
or __repr__
by default:
>>> str(worker)
'<__main__.Person object at 0x...>'
>>> repr(worker)
'<__main__.Person object at 0x...>'
But we could make __str__
use it explicitly:
class Person:
def __init__(self, name, pay):
self.name, self.pay = name, pay
def __format__(self, fmt):
return f'<Person: {self.name}, {self.pay:{fmt}}>'
def __str__(self):
return self.__format__('')