以下是三个Python代码:
======第1号=======
def foo(x, items=[]):
items.append(x)
return items
foo(1) #return [1]
foo(2) #return [1,2]
foo(3) #return [1,2,3]
======第二号========
def foo(x, items=None):
if items is None:
items = []
items.append(x)
return items
foo(1) #return [1]
foo(2) #return [2]
foo(3) #return [3]
======第3号=======
def foo(x, items=[]):
items.append(x)
return items
foo(1) # returns [1]
foo(2,[]) # returns [2]
foo(3) # returns [1,3]
对于代码 1,由于 items
的值没有提供,我认为它应该始终采用默认值[]。但参数items
行为类似于静态变量,保留其值以供后续使用。 No.2 的代码按照我的预期执行:每次调用 foo 时,items
取默认值None
。至于3号代码,我完全不知道。为什么上面三段代码的执行效果如此不同呢?你可以解释吗?谢谢。
PS:我使用的是 python 3.3.1
最佳答案
"Least Astonishment" and the Mutable Default Argument
这篇 stackoverflow 帖子回答了你的问题,因为 Python 函数是具有状态的对象,“item”命名参数保留多个调用之间的状态。
它有它的用途:
def calculate(a, b, c, memo={}):
try:
value = memo[a, b, c] # return already calculated value
except KeyError:
value = heavy_calculation(a, b, c)
memo[a, b, c] = value # update the memo dictionary
return value
关于python - 如何解释这三个python代码的执行结果呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18370109/