关于Python默认参数,假如默认参数是可变(mutable)对象是会有副作用的,一个函数参数的默认值,仅仅在该函数定义的时候,被赋值一次。如此,只有当函数第一次被定义的时候,才将参数的默认值初始化到它的默认值(如一个空的列表)
如:
>>> def function(data=[]):
data.append(1)
return data
>>> function()
[1]
>>> function()
[1, 1]
>>> function()
[1, 1, 1]
当def function(data=[])执行完成,预先计算的值,即data就会被每次函数调用所使用,尤其是当默认参数是可变的对象时,参数可以"类比为全局变量,当然这个全局变量的范围是在函数范围内的"
引用其他博文所说:“
“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 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. 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
def whats_on_the_telly(penguin=None):
if penguin is None:
penguin = []
penguin.append("property of the zoo")
return penguin
def f(x, I=[]): # 函数初始化定义,I仅仅被赋值一次
print('程序运行前I的值为: {}'.format(I))
for i in range(x):
I.append(i*i)
print('I id is : {} '.format(id(I)))
f(2) # 函数被调用,会从初始化义读取I值,并且更改I值f(2,[3,2,1]) # 函数重新调用,I参数被赋值f(3) # 函数重新调用,虽然在函数体内I被重新赋值为空[],但是调用I的值是在初始化的定义的值程序运行前I的值为: []I id is : 42474792
程序运行前I的值为: [3, 2, 1]
I id is : 42474872
程序运行前I的值为: [0, 1]
I id is : 42474792