小编Fen*_*ang的帖子

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

我是一个python初学者,阅读'python tutorial',它说如果我们有一个函数:

def f(a, L=[]):
     L.append(a)
     return L
print f(1)
print f(2)
print f(3)
Run Code Online (Sandbox Code Playgroud)

这将打印

[1]
[1, 2]
[1, 2, 3]
Run Code Online (Sandbox Code Playgroud)

因为默认值只计算一次而list是可变对象.我能理解.

它说继续,如果我们不希望在后续调用之间共享默认值,我们可以:

def f(a, L=None):
   if L is None:           #line  2
       L = []            
   L.append(a)
   return L
print f(1)            
print f(2)
print f(3)
Run Code Online (Sandbox Code Playgroud)

这将输出:

[1]
[2]
[3]
Run Code Online (Sandbox Code Playgroud)

为什么呢?怎么解释这个.我们知道默认值只是被评估once,当我们调用f(2)时,L不是None而且if(第2行)不能为真,所以L.append(a)== [1,2].我可以猜出由于某种原因再次评估默认值,但是什么是'某种原因',只是因为python解释器看到了if L is None: L = []

python parameters function

30
推荐指数
3
解决办法
4908
查看次数

标签 统计

function ×1

parameters ×1

python ×1