首先看一下官方教程中给出的例子:
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)
for kw in keywords:
print(kw, ":", keywords[kw])
想必大部分人都是学过C/C++语言的,看到参数列表你可能会想到C语言中的指针。但是Python语言中并没有指针这个概念。
接下来看一下该函数的调用以及输出结果:
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.
----------------------------------------
shopkeeper : Michael Palin
client : John Cleese
sketch : Cheese Shop Sketch
其实这里涉及到一个概念:
在定义函数时,*代表收集参数,**代表收集关键字参数。
*arguments用来收集参数:"It’s very runny, sir."和 “It’s really very, VERY runny, sir.”
**keywords用来收集关键字参数: shopkeeper=“Michael Palin”、client="John Cleese"和sketch=“Cheese Shop Sketch”