gpt4 book ai didi

python - 修改python的字符串Formatter

转载 作者:行者123 更新时间:2023-12-04 20:46:42 25 4
gpt4 key购买 nike

我有一个不接受任何参数并返回一个字符串的函数,我想使用字符串格式调用它。在这里,这是我尝试使用 format 的方式:

def cabbages():
return 'hello'

In [2]: '{cabbages} world'.format(**locals())
Out[2]: '<function cabbages at 0x101f75578> world'

In [3]: '{cabbages()} world'.format(**locals())
KeyError: 'cabbages()'

所以这两个都不是我想要的,即 cabbages() 的值.

PEP 3101描述了 string.Formatter 的某种方式可以被覆盖,但它似乎没有给出很多例子。如何子类化/自定义字符串 Formatter 类来做这个?

我考虑过的一个hacky 是覆盖 __getattr__ cabbages的方法, 而我 真的不想被“认为是病态的”(或者,至少,*那* 病态的)。

最佳答案

我想我在你的回答中看到的主要缺陷是它不能处理原始的复合字段名称语法,如 0.name对于 'getattr'/'dot' 操作符访问也不是,0[name]用于 PEP 3101 中指定的“getitem”检索。

这是一个适用于 Python 2.7 和 3.3 的版本。一个主要的实现差异是它覆盖了 get_value()方法而不是 get_field() .

虽然它如何检测 get_value() 中的调用有点棘手。方法,我不认为它会被认为是病态的。 ;-)

from __future__ import print_function

from string import Formatter

class CallFormatter(Formatter):
try: # deal with Py 2 & 3 difference
NUMERICS = (int, long)
except NameError:
NUMERICS = int

def get_value(self, key, args, kwargs):
if key.endswith('()'): # call?
return kwargs[key[:-2]]()
elif isinstance(key, self.NUMERICS):
return args[key]
else:
return kwargs[key]

if __name__ == '__main__':
fmt = CallFormatter()

def cabbages():
return 'hello'

d = dict(name='Fred')

class Thing(object):
def __init__(self, value):
self.attr = value
th = Thing(42)

print('d[name]:{d[name]}, th.attr:{th.attr}, '
'cabbages:{cabbages}'.format(**locals()))
print(fmt.format('d[name]:{d[name]}, th.attr:{th.attr}, '
'cabbages:{cabbages}, cabbages():{cabbages()}',
**locals()))

输出:

d[name]:Fred, th.attr:42, cabbages:<function cabbages at 0x00BB05F0>
d[name]:Fred, th.attr:42, cabbages:<function cabbages at 0x00BB05F0>,
cabbages():hello

关于python - 修改python的字符串Formatter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16752818/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com