我正在学习 Python,我正在处理Mutable Default Argument 问题。
# 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
值并且仍然是错误的。
为什么不是?我错过了什么概念?a_list
每次运行时如何擦干净good_append
?