我学习Python到了处理可变默认参数问题的阶段,参考这个。
# BAD: if `a_list` is not passed in, the default will wrongly retain its contents between successive function calls
def bad_append(new_item, a_list=[]):
a_list.append(new_item)
return a_list
# GOOD: if `a_list` is not passed in, the default will always correctly be []
def good_append(new_item, a_list=None):
if a_list is None:
a_list = []
a_list.append(new_item)
return a_list
我知道a_list
只在第一次遇到def
语句时初始化,这就是为什么后续对bad_append
的调用会使用同一个列表对象。我不明白的是为什么
good_append
表现得不同。看起来a_list
仍然只会被初始化一次;因此,if
语句只会在函数第一次调用时为真,这意味着a_list
只会在第一次调用时被重置为[]
,这意味着它仍然会累积所有过去的new_item
值,并且仍然有错误。为什么它不是这样的呢?我缺少哪些概念?每次运行
good_append
时,a_list
是如何被清空的?