2011-10-15 52 views
0

可能重複:
「Least Astonishment」 in Python: The Mutable Default Argument可選參數與表追加

這是非常奇怪的,在Python的可選列表參數功能之間持久的使用.append(來電時) 方法。

def wtf(some, thing, fields=[]): 
    print fields 
    if len(fields) == 0: 
     fields.append('hey'); 
    print some, thing, fields 

wtf('some', 'thing') 
wtf('some', 'thing') 

輸出:

[] 
some thing ['hey'] 
['hey'] # This should not happen unless the fields value was kept 
some thing ['hey'] 

爲什麼在 「字段」 列表包含 「哎」,當它是一個參數?我知道這是本地範圍,因爲我不能在函數外部訪問它,但函數會記住它的值。

回答

3

默認值只計算一次,因此使用可變類型作爲默認值會產生意外的結果。你最好做這樣的事情:

def wtf(some, thing, fields = None): 
    if fields is None: 
    fields = [] 
+0

請注意,如果你曾經調用'wtf('some','thing',something)'這將不會拯救你。現在'something'有一個額外的''嘿'''結尾。 – Ben

+0

怎麼樣?如果「某些東西」是一個列表,那麼它不會是無,所以「字段」將等於「某事」不是嗎? –