实施object.__format__() method https://docs.python.org/3/reference/datamodel.html#object.__format__相反,用户可以指定所需的格式format()功能 https://docs.python.org/3/library/functions.html#format and str.format() method https://docs.python.org/3/library/stdtypes.html#str.format:
print(format(obj, 'pretty'))
or
print('This object is pretty: {:pretty}'.format(obj))
您可能希望将大部分格式处理委托给str.__format__
:
def __format__(self, spec):
if spec.endswith('pretty'):
prettified = self.pretty_version()
return prettified.__format__(spec[:-6])
return str(self).__format__(spec)
这样您仍然可以支持默认的所有字段宽度和填充对齐选项str.__format__
方法支持。
Demo:
>>> class Foo():
... def __str__(self):
... return 'plain foo'
... def pretty_version(self):
... return 'pretty foo'
... def __format__(self, spec):
... if spec.endswith('pretty'):
... prettified = self.pretty_version()
... return prettified.__format__(spec[:-6])
... return str(self).__format__(spec)
...
>>> f = Foo()
>>> print(f)
plain foo
>>> print(format(f))
plain foo
>>> print(format(f, 'pretty'))
pretty foo
>>> print(format(f, '>20pretty'))
pretty foo
>>> print('This object is pretty: {:^20pretty}!'.format(f))
This object is pretty: pretty foo !