<p>不能在占位符中调用方法。您可以访问属性和属性,甚至为值编制索引,但不能调用方法:</p>
<pre><code>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())
</code></pre>
<p>方法示例(失败):</p>
<pre><code>>>> 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()'
</code></pre>
<p>具有属性(工作)的示例:</p>
<pre><code>>>> 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']"
</code></pre>
<p>格式化语法清楚地表明,您只能访问属性(a la<code>getattr</code>)或索引(a la<code>__getitem__</code>)占位符(取自<a href="https://docs.python.org/library/string.html#format-string-syntax" rel="noreferrer">"Format String Syntax"</a>):</p>
<blockquote>
<p>The arg_name can be followed by any number of index or attribute expressions. An expression of the form <code>'.name'</code> selects the named attribute using <code>getattr()</code>, while an expression of the form <code>'[index]'</code> does an index lookup using <code>__getitem__()</code>.</p>
</blockquote>
<hr/>
<p>使用Python 3.6,您可以使用f字符串轻松完成此操作,甚至不必传入<code>locals</code>:</p>
<pre><code>>>> 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']"
</code></pre>