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']
爲什麼在 「字段」 列表包含 「哎」,當它是一個參數?我知道這是本地範圍,因爲我不能在函數外部訪問它,但函數會記住它的值。
請注意,如果你曾經調用'wtf('some','thing',something)'這將不會拯救你。現在'something'有一個額外的''嘿'''結尾。 – Ben
怎麼樣?如果「某些東西」是一個列表,那麼它不會是無,所以「字段」將等於「某事」不是嗎? –