python函数关键字参数_[python 函数学习篇] 关键字参数

函数可以通过 关键字参数 的形式来调用,形如 keyword =value 。例如,以下的函数:

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, "!"接受一个必选参数 ( voltage ) 以及三个可选参数 ( state , action , 和 type )。 可以用以下的任一方法调用:

parrot(1000) # 1positional argument

parrot(voltage=1000) # 1keyword argument

parrot(voltage=1000000, action='VOOOOOM') # 2keyword arguments

parrot(action='VOOOOOM', voltage=1000000) # 2keyword arguments

parrot('a million', 'bereft of life', 'jump') # 3positional arguments

parrot('a thousand', state='pushing up the daisies') # 1 positional, 1keyword

不过以下几种调用是无效的:

parrot() # required argument missing

parrot(voltage=5.0, 'dead') # non-keyword argument after a keyword argument

parrot(110, voltage=220) # duplicate value forthe same argument

parrot(actor='John Cleese') # unknown keyword argument

通常,参数列表中的每一个关键字都必须来自于形式参数,每个参数都有对应的关键字。形式参数有没有默认值并不重要。实际参数不能一次赋多个值——形式 参数不能在同一次调用中同时使用位置和关键字绑定值。这里有一个例子演示了在这种约束下所出现的失败情况:>>>def function(a):

... pass

...>>> function(0, a=0)

Traceback (most recent call last):

File"", line 1, in ?TypeError: function() got multiple valuesfor keyword argument 'a'引入一个形如**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", kindfor arg inarguments:

print arg

print"-" * 40keys=sorted(keywords.keys())for kw inkeys:

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 outof Limburger

It's very runny, sir.

It's really very, VERY runny, sir.

----------------------------------------client : John Cleese

shopkeeper : Michael Palin

sketch : Cheese Shop Sketch

注意在打印 关键字 参数字典的内容前先调用 sort() 方法。否则的话,打印参数时的顺序是未定义的。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值