4.7.1 参数默认值 Default Argument Values

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

最有用的形式是给一个或多个参数指定默认值。这样创建的函数可以在调用时使用较少的参数。

def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
    while True:
        ok = raw_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 either like this: ask_ok('Do you really want to quit?') or like this: ask_ok('OK to overwrite the file?', 2).

这个函数还可以用以下的方式调用:ask_ok('Do you really want to quit?'),或者像这样:ask_ok('OK to overwrite the file?', 2)

The default values are evaluated at the point of function definition in the defining scope, so that

默认值在函数定义段被解析,如下所示:

i = 5

def f(arg=i):
    print arg

i = 6
f()

will print 5.

将得到 5.

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