python函数中的可选参数及其默认值

Optional parameters in Python functions and their default values

本问题已经有最佳答案,请猛点这里访问。

Possible Duplicate:
“Least Astonishment” in Python: The Mutable Default Argument

我对可选参数在Python函数/方法中的工作方式有点困惑。

我有以下代码块:

1
2
3
4
5
6
7
8
9
>>> def F(a, b=[]):
...     b.append(a)
...     return b
...
>>> F(0)
[0]
>>> F(1)
[0, 1]
>>>

为什么F(1)返回[0, 1],而不是[1]

我是说,里面发生了什么?


几年前Pycon的Good Doc-解释了默认参数值。但基本上,由于列表是可变对象,关键字参数在函数定义时进行计算,所以每次调用函数时,都会得到相同的默认值。

正确的方法是:

1
2
3
4
5
def F(a, b=None):
    if b is None:
        b = []
    b.append(a)
    return b

从直观上看,默认参数有点像函数对象上的成员变量。

Default parameter values are evaluated when the function definition is executed. This means that the expression is evaluated once, when the function is defined, and that same"pre-computed" value is used for each call. This is especially important to understand when a default parameter is a mutable object, such as a list or a dictionary: if the function modifies the object (e.g. by appending an item to a list), the default value is in effect modified.

http://docs.python.org/reference/compound-stmts.html函数

Lists are a mutable objects; you can change their contents. The correct way to get a default list (or dictionary, or set) is to create it at run time instead, inside the function:

1
2
3
4
5
def good_append(new_item, a_list=None):
    if a_list is None:
        a_list = []
    a_list.append(new_item)
    return a_list