可能重複:
「Least Astonishment」 in Python: The Mutable Default Argument參數值正確性
當我閱讀下面的講義:http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#other-languages-have-variables
我碰到下面的例子。基本上,它聲稱:
def bad_append(new_item, a_list=[]):
a_list.append(new_item)
return a_list
不追加項目名單,因爲a_list
在在函數定義時計算的最佳途徑。
取而代之的是,更好的選擇是:
def good_append(new_item, a_list=None):
if a_list is None:
a_list = []
a_list.append(new_item)
return a_list
,因爲它定義了功能的運行時變量。
來自C背景,是不是a_list
這裏是一個局部變量?它如何將一個函數調用的值存儲到另一個函數調用中?此外,有人可以詳細說明爲什麼第二個例子比第一個更好嗎?在定義中定義函數有什麼問題?它似乎不會覆蓋原始值或任何東西。
謝謝!
我想你可以閱讀以下內容:http://stackoverflow.com/questions/1132941/least-astonishment-in-python-the-mutable-default-argument – Abgan
看看http://docs.python .org/faq/design.html – Pramod
我認爲這將是這個問題的第78個重複。 –