Special Method Protocols

__format__() — object lifecycle protocol

Customize format(obj, spec) and formatted string replacement fields. Interpret the supplied specification; return str. The default object implementation rejects nonempty specifications.

Formal Syntax & Structure

python syntaxpython
def __format__(self, format_spec):

Parameters & Attributes

NameTypeDescription
format_specstrFormat specification, possibly empty.

Return Value

str

Formatted text.

Working Example

Example Snippetpython
class Score:    def __format__(self, format_spec): return format(7, format_spec)print(format(Score(), "03d"))
Python Reference