函数python的默认值

Ale*_*xey 0 python

我试图理解这个问题和答案:

python函数默认参数只评估一次?

为了理解它,我尝试:

def f1(a, L=[]):
    if not L:
        print "L is empty"
        L = []
    L.append(a)
    return L

>>>f1(1)
L is empty
[1]
>>>f1(1)
L is empty
[1]

def f2(a, L=[]):
        if L:
            print "L isn't empty"
            L = []
        L.append(a)
        return L

>>>f2(1)
[1]
>>>f2(1)
L isn't empty
[1]
Run Code Online (Sandbox Code Playgroud)

因此,我认为在f1 L每次再次变空的情况下- []在每次调用之后再次分配f1.但是,如果f2 L是某种程度上不是空的?为什么?

bad*_*adp 6

当你这样做:

L = []
Run Code Online (Sandbox Code Playgroud)

...你没有改变引用的值L; 您将引用 更改L为指向全新列表[].

如果要在L不更改引用本身的情况下清空引用的列表,可以编写:

del L[:]
Run Code Online (Sandbox Code Playgroud)

...或使用方法,如removepop通过改变当前列表的工作.


这里是动画形式的f1和f2,以帮助您理解.(点击webm.等待每个gif淡入白色.GIF不同步,抱歉.)

F1

F2