问题描述
有什么方法可以改变 Formatter
python的 string.format()
使用?我有一个自定义的(禁用 check_unused_args
方法),但这需要我使用 formatter.format(text)
语法,而不是text.format()
语法,我更喜欢。 我能否以某种方式换出默认格式化程序?
注意:这只是一个小项目,我不需要担心图书馆或其他东西的混乱。
没有。我认为理性是因为它会导致代码混乱。人们会期望 format_string.format(...)
表现出一种行为方式,它的表现会有所不同,导致错误和普遍的悲伤。
$ b
然而,您可以显式告诉python您想要使用不同的格式化程序。
class MyFormatter(string.Formatter):
这是我的格式化程序,比标准程序更好。
#customization here ...
MyFormatter()。format(format_string,* args,** kwargs)
通过继承 string.Formatter
,您可以访问整个 Formatter
API,如果这还不够,可以使用 __格式__
自定义对象的格式。钩子方法 Formatter
对象调用(包括标准的)
Is there some way I can change the Formatter
python's string.format()
uses? I have a custom one (disables the check_unused_args
method), but this requires me use the formatter.format("text")
syntax, instead of the "text".format()
syntax, which I'd prefer.
Can I swap out the 'default formatter' somehow?
NOTE: This is just a small project, I don't need to worry about messing up libraries or anything.
No. I think the rational is because it would lead to really confusing code. People would expect format_string.format(...)
to behave one way, and it would behave differently causing bugs and general sadness.
You can however, explicitly tell python that you want to use a different formatter.
class MyFormatter(string.Formatter):
"""This is my formatter which is better than the standard one."""
# customization here ...
MyFormatter().format(format_string, *args, **kwargs)
By inheriting from string.Formatter
, you gain access to the entire Formatter
API which can make your custom formatter work better.
If that weren't enough, you can customize how objects format themselves using the __format__
hook method which Formatter
objects call (including the standard one).
这篇关于我如何重写Python中的默认字符串格式化程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!