C++,python,热爱算法和机器学习
全部博文(1214)
分类: Python/Ruby
2015-01-01 21:11:15
def foo(x=[]): x.append(1); print(x)
foo(); foo()
得到:
[1]
[1, 1]
第一次调用foo() 得到x =[] ,然后x = [1],x指向列表[1]内存中的地址。
但是第二次调用foo() , 不执行x = []
参考 Python 官方 Tutorial 中的内容
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:
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:
[1]
The default values are evaluated at the point of function definition in the defining scope, so that will print 5
[2]
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: