2012-07-17 87 views
-1

可能重複:
「Least Astonishment」 in Python: The Mutable Default Argument爲什麼這兩個append方法會產生不同的結果?

我試圖理解下面的兩種方法之間的區別:

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

你的名字不匹配..'bad_append'等... – Levon 2012-07-17 19:57:40

回答

0

功能second_append始終爲您創建一個新的本地列表中的每個被調用時。

相關問題