问题描述
我想创建一个 __str__
方法,根据用户选择创建各种格式的字符串.
我想出的最好的方法是制作一个 __str__(**kwargs)
方法,这似乎可以正常工作,但它与 str(obj) 不兼容
或 print(obj)
.换句话说,我必须使用 print(obj.__str__(style='pretty'))
而不是 print(obj, style='pretty')
.
实施 object.__format__()
方法,然后用户可以使用 format()
函数 和 str.format()
方法:
print(format(obj, 'pretty'))
或
print('这个对象很漂亮:{:pretty}'.format(obj))
您可能希望将大部分格式处理委托给 str.__format__
:
def __format__(self, spec):if spec.endswith('漂亮'):美化 = self.pretty_version()返回 prettified.__format__(spec[:-6])返回 str(self).__format__(spec)
这样您仍然可以支持默认 str.__format__
方法支持的所有字段宽度和填充对齐选项.
演示:
>>>类 Foo():... def __str__(self):... 返回 'plain foo'...定义漂亮版本(自我):...返回'漂亮的foo'... def __format__(self, spec):...如果 spec.endswith('pretty'):... 美化 = self.pretty_version()...返回 prettified.__format__(spec[:-6])...返回 str(self).__format__(spec)...>>>f = Foo()>>>打印(f)纯 foo>>>打印(格式(f))纯 foo>>>打印(格式(f,'漂亮'))漂亮的 foo>>>打印(格式(f,'> 20pretty'))漂亮的 foo>>>print('这个对象很漂亮:{:^20pretty}!'.format(f))这个对象很漂亮:漂亮的 foo !I'd like to create a __str__
method that creates the string in various formats according to user choice.
The best I have come up with is to make a __str__(**kwargs)
method, and this seems to work ok, but it isn't compatible with str(obj)
or print(obj)
. In other words I have to use print(obj.__str__(style='pretty'))
rather than print(obj, style='pretty')
.
Implement the object.__format__()
method instead, and a user can then specify the formatting required with the format()
function and str.format()
method:
print(format(obj, 'pretty'))
or
print('This object is pretty: {:pretty}'.format(obj))
You probably want to delegate most of the handling of the format on to str.__format__
:
def __format__(self, spec):
if spec.endswith('pretty'):
prettified = self.pretty_version()
return prettified.__format__(spec[:-6])
return str(self).__format__(spec)
That way you can still support all the field width and padding alignment options that the default str.__format__
method supports.
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 !
这篇关于用不同的格式选项实现 __str__ 方法的 Pythonic 方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!