原文地址:http://docs.pythontab.com/python/python3.4/controlflow.html#tut-functions
函數可以通過 關鍵字參數 的形式來調用,形如 keyword = value 。例如,以下的函數:
def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'): print("-- This parrot wouldn't", action, end=' ') print("if you put", voltage, "volts through it.") print("-- Lovely plumage, the", type) print("-- It's", state, "!")
接受一個必選參數 (voltage) 以及三個可選參數 (state, action, 和 type).
可以用以下方法調用:
parrot(1000) # 1 positional argument parrot(voltage=1000) # 1 keyword argument parrot(voltage=1000000, action='VOOOOOM') # 2 keyword arguments parrot(action='VOOOOOM', voltage=1000000) # 2 keyword arguments parrot('a million', 'bereft of life', 'jump') # 3 positional arguments parrot('a thousand', state='pushing up the daisies') # 1 positional, 1 keyword
不過以下幾種調用是無效的:
parrot() # required argument missing parrot(voltage=5.0, 'dead') # non-keyword argument after a keyword argument parrot(110, voltage=220) # duplicate value for the same argument parrot(actor='John Cleese') # unknown keyword argument
引入一個形如 **name 的參數時,它接收一個字典(參見 typesmapping ) ,該字典包含了所有未出現在形式參數列表中的關鍵字參數。這里可能還會組合使用一個形如 *name (下一小節詳細介紹) 的形式參數,它接收一個元組(下一節中會詳細介紹),包含了所有沒有出現在形式參數列表中的參數值。( *name 必須在 **name 之前出現) 例如,我們這樣定義一個函數:
def cheeseshop(kind, *arguments, **keywords): print("-- Do you have any", kind, "?") print("-- I'm sorry, we're all out of", kind) for arg in arguments: print(arg) print("-" * 40) keys = sorted(keywords.keys()) for kw in keys: print(kw, ":", keywords[kw])
它可以像這樣調用:
cheeseshop("Limburger", "It's very runny, sir.", "It's really very, VERY runny, sir.", shopkeeper="Michael Palin", client="John Cleese", sketch="Cheese Shop Sketch")
當然它會按如下內容打印:
-- Do you have any Limburger ? -- I'm sorry, we're all out of Limburger It's very runny, sir. It's really very, VERY runny, sir. ---------------------------------------- client : John Cleese shopkeeper : Michael Palin sketch : Cheese Shop Sketch
注意在打印 關鍵字 參數字典的內容前先調用 sort() 方法。否則的話,打印參數時的順序是未定義的