您的位置:首页 > 编程语言 > Python开发

4.7.2. Keyword Arguments(关键字参数)

2016-01-11 16:26 417 查看
函数也可以像 形参=值 这样用关键字参数。例如下面的函数:

def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
print "-- This parrot wouldn't", action,
print "if you put", voltage, "volts through it."
print "-- Lovely plumage, the", type
print "-- It's", state, "!"要求一个必要的参数,3个可选的参数(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在一个函数调用中,关键字参数必须在固定的参数后面。所有的关键字参数必须匹配函数中的某个形参(比如 actor在parrot函数中不被接受),并且关键字参数的调用顺序无关紧要。这也包括必选参数(比如,parrot(voltage=1000)就是正确的)。同一个参数不可以传给函数多次,下面例子说明了这个限制:
>>> def function(a):
... pass
...
>>> function(0, a=0)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: function() got multiple values for keyword argument 'a'

最后一个要将的参数 **name是个奇葩,它接收任意个关键字参数。还有一种参数 *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注意关键字参数的名字是按字典的keys()方法的输出方式输出的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python 关键字参数