1、定义有多个参数的函数,有三种形式:
一、Default Argument 为一个或多个参数确定默认值是最有用的一种形式。这可以使得一个函数在尽可能少参数的情况下使用
def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
while True:
ok = input(prompt)
if ok in ('y', 'ye', 'yes'):
return True
if ok in ('n', 'no', 'nop', 'nope'):
return False
retries = retries - 1
if retries < 0:
raise IOError('uncooperative user')
print(complaint)
调用该函数可以:
· 只给定一个参数:ask_ok('Do you really want to quit?')
· 两个参数:ask_ok('Ok to overwrite the file?',2)
· 所有参数:ask_ok('Ok to overwrite the file?',2,'Come on, only yes or no!')
此外,这个函数介绍来 in 关键字,用于判断一个序列是否包含某个值
一(1)、注意,默认值只在 定义域 确定,所以下面的程序会打印出 5
i = 5
def f(arg=i):
print(arg)
i = 6
f()
一(2)、重要提示:默认值只会 评估 一次,这会使得易变的对象,例如 list,dictionary,或者大多数类的实例,出现意想不到的结果:例如下面的函数会累计每次调用时传入的参数:
def f(a, L=[]):
L.append(a)
return L
print(f(1))
print(f(2))
print(f(3))
这会打印出:
[1]
[1, 2]
[1, 2, 3]
如果不想这样,可以这样调用:
def f(a, L=None):
if L is None:
L = []
L.append(a)
return L
二、关键字参数 Keyword Arguments
二(1)、函数可以以 关键字参数 的形式:warg = 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(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
注意几点:(1)关键字参数(keyword arguments)必须跟在 位置参数(positional arguments) 后面;
(2)所有的 关键字参数 必须匹配函数接受的 参数 之一,而不在乎他们的位置;
(3)没有参数可以接受一个值超过一次,所以下面的例子会由于这样的限制遭到限制:
>>> def function(a):
... pass
...
>>> function(0, a=0)
Traceback (most recent call last):
File "
TypeError: function() got multiple values for keyword argument 'a'
三、形式参数 Formal Arguments
- **name。它接受一个字典,这个字典包含除形式参数之外的所有 关键字参数(键值对 k = v)。另一种形式参数 *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 排序了,否则打印出来的顺序是不确定的