您不能在占位符中调用方法。您可以访问属性和属性,甚至可以索引值 - 但不能调用方法:
class Fun(object):
def __init__(self, vals):
self.vals = vals
@property
def keys_prop(self):
return list(self.vals.keys())
def keys_meth(self):
return list(self.vals.keys())
方法示例(失败):
>>> foo = Fun({'one key': 'one value', 'second key': 'second value'})
>>> "In the middle of a string: {foo.keys_meth()}".format(foo=foo)
AttributeError: 'Fun' object has no attribute 'keys_meth()'
属性示例(工作):
>>> foo = Fun({'one key': 'one value', 'second key': 'second value'})
>>> "In the middle of a string: {foo.keys_prop}".format(foo=foo)
"In the middle of a string: ['one key', 'second key']"
格式化语法清楚地表明您只能访问属性(a lagetattr
)或索引(a la__getitem__
)占位符(取自“格式化字符串语法”):
arg_name 后面可以跟任意数量的索引或属性表达式。形式的表达'.name'
使用选择命名属性getattr()
,而形式的表达式'[index]'
使用索引查找__getitem__()
.
使用 Python 3.6,您可以使用 f 字符串轻松地做到这一点,您甚至不必传入locals
:
>>> foo = {'one key': 'one value', 'second key': 'second value'}
>>> f"In the middle of a string: {foo.keys()}"
"In the middle of a string: dict_keys(['one key', 'second key'])"
>>> foo = {'one key': 'one value', 'second key': 'second value'}
>>> f"In the middle of a string: {list(foo.keys())}"
"In the middle of a string: ['one key', 'second key']"