Possible Duplicate:
“Least Astonishment” in Python: The Mutable Default Argument
我试图理解以下两种方法之间的区别:
def first_append(new_item, a_list=[]):
a_list.append(new_item)
return a_list
def second_append(new_item, a_list=None):
if a_list is None:
a_list = []
a_list.append(new_item)
return a_list
first_append
在多次调用时不断添加到a_list
,导致它增长。但是,second_append
总是返回长度为1的列表。这里有什么区别?你知道吗
示例:
>>> first_append('one')
['one']
>>> first_append('two')
['one', 'two']
>>> second_append('one')
['one']
>>> second_append('two')
['two']
函数
second_append
每次调用时都会为您创建一个新的本地列表。你知道吗相关问题 更多 >
编程相关推荐