【发布时间】:2015-09-01 08:18:29
【问题描述】:
我正在阅读 Python Documentation Release 2.7.10 中的 python 教程,我遇到了类似这样的内容。
代码
def fun1(a,L=[]):
L.append(a)
return L
print fun1(1)
print fun1(2)
print fun1(3)
def fun2(a,L = None):
if L is None:
L=[]
L.append(a)
return L
print fun2(1)
print fun2(2)
print fun2(3)
输出
[1]
[1, 2]
[1, 2, 3]
[1]
[2]
[3]
Process finished with exit code 0
如果第一个函数fun1() 中的L=[] 只被调用一次,则fun1() 的输出很好。但是为什么L=None 每次都在fun2() 中被调用。
【问题讨论】:
-
“为什么
L=None每次都没有被调用” – 我不知道你想说什么。 -
我假设
L=None每次都被调用/执行。这就是为什么条件if L is None在第二个函数fun2()中每次都为真。 -
默认参数在函数声明时进行评估。空列表是可变的,因此在每个函数调用中您都在编辑相同的列表。附加到它不会创建新对象。使用 None 时,在函数体中创建列表。每次从函数返回新列表。
标签: python python-2.7 arguments default-arguments