【问题标题】:How can I override the default string formatter in python?如何覆盖python中的默认字符串格式化程序?
【发布时间】:2016-01-14 14:00:25
【问题描述】:

有什么方法可以改变Formatter python 的string.format() 用途吗?我有一个自定义的(禁用check_unused_args 方法),但这需要我使用formatter.format("text") 语法,而不是我更喜欢的"text".format() 语法。

我可以以某种方式换掉“默认格式化程序”吗?

注意:这只是一个小项目,我不需要担心弄乱库或任何东西。

【问题讨论】:

  • 您可以从内置的字符串类中派生出您自己的字符串类,并提供您自己的format 方法。
  • 另见:pyformat.info

标签: python string formatting


【解决方案1】:

有什么方法可以改变 Formatter python 的 string.format() 使用吗?

没有。我认为理性是因为它会导致代码非常混乱。人们会期望 format_string.format(...) 以一种方式行事,它的行为会有所不同,从而导致错误和普遍的悲伤。


但是,您可以明确告诉 python 你想使用不同的格式化程序。

class MyFormatter(string.Formatter):
    """This is my formatter which is better than the standard one."""
    # customization here ...

MyFormatter().format(format_string, *args, **kwargs)

通过从string.Formatter 继承,您可以访问整个Formatter API,这可以使您的自定义格式化程序更好地工作。

如果这还不够,您可以使用Formatter 对象调用的__format__ 钩子方法(包括标准方法)自定义对象的格式。

【讨论】:

  • 哇,太糟糕了。不过我明白其中的道理。这是我一直在使用的解决方案。
  • 与其他语言(例如 Ruby)不同,Python 通常不允许您修改内置类型(例如字符串)。我个人认为这是一件好事——它迫使你变得明确。但是,当然其他人可能不同意。 :-)
  • 我认为您只需替换 str.format = MyFormatter().format 即可将默认格式更改为您的实现。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-03-26
  • 1970-01-01
  • 1970-01-01
  • 2016-04-13
  • 2011-11-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多