More on Defining Functions--- Default Argument Values
It is also possible to define functions with a variable number of arguments. There are three forms, which can be combined.定义函数时也可以添加一些参数.有三种形式,可以组合使用.
The most useful form is to specify a default value for one or more arguments. This creates a function that can be called with fewer arguments than it is defined to allow. For example:为一个或多个参数指定默认值是最有用的形式.这样会创建一个函数,其参数可少于定义的数量.例如:
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('refusenik user')
print(complaint)
This function can be called in several ways:这个函数可以几种方法被调用:
giving only the mandatory argument: ask_ok('Do you really want to quit?')
giving one of the optional arguments: ask_ok('OK to overwrite the file?', 2)
or even giving all arguments: ask_ok('OK to overwrite the file?', 2, 'Come on, only yes or no!')
This example also introduces the in keyword. This tests whether or not a sequence contains a certain value.这个例子中引用了关键字in.它将测试一个序列是否含有某个值.
The default values are evaluated at the point of function definition in the defining scope, so that will print 5.默认值在函数定义的范围内被赋值,所以此处将打印值5.
i = 5
def f(arg=i):
print(arg)
i = 6
f()
Important warning: The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes. For example, the following function accumulates the arguments passed to it on subsequent calls:重要警告:默认值只被赋予一次.这在默认值为列表,字典或大部分类的实例等可变对象时会产生很大影响.例如,下面的函数将在子序列调用时积累传递给它的参数:
def f(a, L=[]):
L.append(a)
return L
print(f(1))
print(f(2))
print(f(3))
This will print以上将打印以下结果
[1]
[1, 2]
[1, 2, 3]
If you don’t want the default to be shared between subsequent calls, you can write the function like this instead:如果您不想和子序列调用共享默认值,您可以用以下写法替换:
def f(a, L=None):
if L is None:
L = []
L.append(a)
return L