【发布时间】:2014-03-11 15:14:01
【问题描述】:
我正在阅读 Python 库的教程。找到这个示例代码:
>>> device = monitor.poll(timeout=3)
>>> if device:
... print('{0.action}: {0}'.format(device))
...
我知道 {0} 的含义,并且在这个 .format() 模板中。 {0.action} 是什么意思,如何处理?
【问题讨论】:
我正在阅读 Python 库的教程。找到这个示例代码:
>>> device = monitor.poll(timeout=3)
>>> if device:
... print('{0.action}: {0}'.format(device))
...
我知道 {0} 的含义,并且在这个 .format() 模板中。 {0.action} 是什么意思,如何处理?
【问题讨论】:
一个有启发性的例子:
>>> class Device:
def __init__(self):
self.action = "bar"
def __str__(self):
return "foo"
>>> device = Device()
>>> print('{0.action}: {0}'.format(device))
bar: foo
“点符号”instance.attribute 可用于访问 str.format 中的属性,就像在其他地方一样。
【讨论】: