为什么这两个append方法产生不同的结果?

2024-04-25 02:05:02 发布

您现在位置:Python中文网/ 问答频道 /正文

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']

Tags: nonenewreturndefitemonelistfirst