.
-- Lovelyplumage, the Norwegian Blue
-- It's a stiff!
-- This parrotwouldn't VOOOOOM if you put 1000000 volts through it.
-- Lovelyplumage, the Norwegian Blue
-- It's a stiff!
-- This parrotwouldn't jump if you put a million volts through it.
-- Lovelyplumage, the Norwegian Blue
-- It's bereftof life !
-- This parrotwouldn't voom if you put a thousand volts through it.
-- Lovelyplumage, the Norwegian Blue
-- It's pushingup the daisies !
但是下面的调用方式会报错:
parrot() # 必须的参数没有填入
parrot(voltage=5.0, 'dead') # 关键字传参后面的一定也是关键字传参
parrot(110, voltage=220) # 同一个参数传了不同的实参
parrot(actor='John Cleese') # 函数定义中没有这个形参。
关键字实参后面不能再有位置实参。
当必填参数没有时,会报错。
当必填参数以位置实参的方式传递时,默认参数可以按照关键字实参的方式传递,也可以以位置实参的方式传递,而且此时,必填参数一定在默认参数前面。
当必填参数以关键字实参方式传递的时候,默认参数传递的时候也一定是以关键字实参方式传递,而且此时与位置无关。
关键字实参的关键字必须是形参中有的,否则会报错。
(4)任意多数目的参数“*”
最不常使用的选项是指定可以使用任意数量的参数调用的函数。这些参数将被裹在一个元组中。在可变数目的参数之前, 零个或更多的正常参数可能会发生。
def write_multiple_items(file, separator, *args):
file.write(separator.join(args))
通常情况下,可变参数将在参数列表中的最后(含有默认参数的时候,默认参数在可变参数后面。另外,传入字典参数也在可变参数之后,因为字典参数也是一种可变参数)。
在可变参数后面的参数,只能以关键字实参的方式传递,而不能使用位置实参传递方式。
def concat(*args, sep="/"):
return sep.join(args)
print(concat("earth", "mars", "venus"))
print(concat("earth", "mars", "venus",sep="."))
结果为:
>>>
===========RESTART: D:/python/pythonLearning/KeywordArguments.py ===========
earth/mars/venus
earth.mars.venus
(5)需要字典类型的参数“**”
下面例子中**keywords代表传入字典类型的参数,而且*一定要在**之前。
def cheeseshop(kind, *arguments, **keywords):
print("--Do you have any", kind, "?")
print("--I'm sorry, we're all out of", kind)
for arg inarguments:
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")
当然结果如下:
>>>
===========RESTART: D:/python/pythonLearning/KeywordArguments.py ===========
-- Do you haveany Limburger ?
-- I'm sorry,we're all out of Limburger
It's very runny,sir.
It's reallyvery, VERY runny, sir.
----------------------------------------
client : JohnCleese
shopkeeper :Michael Palin
sketch : CheeseShop Sketch
(6)Unpacking Argument Lists(python3.6帮助文档上用的这个词,必应翻译给的翻译是开箱的参数列表,我感觉应该是参数列表的拆包,不够下面还是用了开箱这个词,大家理解下)
这是与之前把数据组合成list相反的操作,即把list中的数据进行开箱操作,把里面的数据全部取出来使用,有点不好理解,看个例子吧
>>> list(range(3,6))
[3, 4, 5]
>>> args=[3,6]
>>> list(range(*args))
[3, 4, 5]
>>> args=(3,6)
>>> list(range(*args))
[3, 4, 5]
>>>这里把args中的数据进行开箱操作,把里面的数据作为range的参数列表.很显然,这个开箱操作对于元组也是适用的.
另外,也可以对字典执行开箱操作,需要的是两个*号即可.
def parrot(voltage, sta