python不可“用可变对象作默认参数”

来源:互联网 发布:project是什么软件 编辑:程序博客网 时间:2024/06/06 06:35

默认参数很有用,但使用不当,也会掉坑里。默认参数有个最大的坑,演示如下:

先定义一个函数,传入一个list,添加一个END再返回:

def add_end(L=[]):    L.append('END')    return L

当你正常调用时,结果似乎不错:

>>> add_end([1, 2, 3])[1, 2, 3, 'END']>>> add_end(['x', 'y', 'z'])['x', 'y', 'z', 'END']

当你使用默认参数调用时,一开始结果也是对的:

>>> add_end()['END']

但是,再次调用add_end()时,结果就不对了:

>>> add_end()['END', 'END']>>> add_end()['END', 'END', 'END']

很多初学者很疑惑,默认参数是[],但是函数似乎每次都“记住了”上次添加了'END'后的list。

原因解释如下:

Python函数在定义的时候,默认参数L的值就被计算出来了,即[],因为默认参数L也是一个变量,它指向对象[],每次调用该函数,如果改变了L的内容,则下次调用时,默认参数的内容就变了,不再是函数定义时的[]了。

https://docs.python.org/2/reference/compound_stmts.html#function-definitions

"Default parameter values are evaluated when the function definition is executed. This means that the expression is evaluatedonce, when the function is defined, and that the 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. This is generally not what was intended. A way around this is to use None as the default, and explicitly test for it in the body of the function.(as shown above)


参考:https://m.aliyun.com/yunqi/wenji/126981