這是因為您可以使用格式迷你語言來訪問對象的屬性.例如,我經常在自己的自定義類工作中使用它.假設我為每臺需要處理的計算機定義了一個類.
class Computer(object):
def __init__(self,IP):
self.IP = IP
而現在我想對整個計算機做一些事情
list_comps = [Computer(name,"192.168.1.{}".format(IP)) for IP in range(12)]
for comp in list_comps:
frobnicate(comp) # do something to it
print("Frobnicating the computer located at {comp.IP}".format(comp=comp))
現在它將打印出來
Frobnicating the computer located at 192.168.1.0
Frobnicating the computer located at 192.168.1.1
Frobnicating the computer located at 192.168.1.2 # etc etc
因為每次,它都會找到我傳遞給formatter(comp)的對象,抓取它的屬性IP,然后使用它.在您的示例中,您為格式化程序提供了類似于屬性訪問器(.)的內容,因此它嘗試訪問在訪問者之前給定的對象,然后查找其定義的屬性.
你的最后一個例子是有效的,因為它正在尋找測試,它找到了它! :符號對格式化程序來說是特殊的,因為它標記了kwarg的結尾和格式迷你語言的開頭.例如:
>>> x = 12.34567
>>> print("{x:.2f}".format(x))
12.34
:之后的.2f告訴字符串格式化程序將參數x視為浮點數并在小數點后2位數后截斷它.這是well documented,我強烈建議你仔細看看這個,并將其加入書簽以備將來使用!這非常有幫助!