python文档中关于默认参数是这样说的:
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 the same “pre-computed” value is used for each call.
因此,如下代码:
def function(data=[]):
print id(data), data
data.append(1)
for i in range(3):
function()
输出结果为:
4462873272 []
4462873272 [1]
4462873272 [1, 1]
一切正像文档中说的那样,data只计算一次,之后的调用返回的是已经计算出来的值(因此,id(data)没有变化,每次append均针对同一个data)。
但是我们带参数调用function时,即:
for i in range(3):
function([])
输出结果为:
4462872984 []
4462872984 []
4462872984 []
data的值是符合预期的,但是三次调用function,id(data)的值竟然也一样,这个是为什么呢?带参数传递时,每次调用都应该是新建data的吧。
认真读文档啊:https://docs.python.org/2/library/functions.html#id 。
Because:
CPython中id的实现概念上相当于对象在内存中的地址。那请看这段代码:
前后是两个不同的list对象,但既然前面一个对象用完就被销毁掉了,那后面的一个list就可能重用相同的内存空间,所以id返回的地址就是一样的了。