为什么采用无固定Python的可变默认参数的问题? [英] Why does using None fix Python's mutable default argument issue?
问题描述
我在点在学习,我正在处理<一个Python href=\"http://stackoverflow.com/questions/1132941/least-astonishment-in-python-the-mutable-default-argument\">the可变默认参数问题。
I'm at the point in learning Python where I'm dealing with the Mutable Default Argument problem.
def bad_append(new_item, a_list=[]):
a_list.append(new_item)
return 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
据我所知,的a_list
仅当第一次遇到 DEF
语句初始化,这就是为什么后续调用 bad_append
使用同一个列表对象。
I understand that a_list
is initialized only when the def
statement is first encountered, and that's why subsequent calls of bad_append
use the same list object.
我不明白的是为什么 good_append
的作品有什么不同。它看起来像的a_list
将还是的仅进行一次初始化;因此,如果
语句只会是真实的在功能上的第一次调用,这意味着的a_list
只会得到重置 []
在第一次调用,这意味着它仍然会积累过去所有的 NEW_ITEM
价值,仍然是马车。
What I don't understand is why good_append
works any different. It looks like a_list
would still be initialized only once; therefore, the if
statement would only be true on the first invocation of the function, meaning a_list
would only get reset to []
on the first invocation, meaning it would still accumulate all past new_item
values and still be buggy.
为什么不呢?我缺少什么概念?如何的a_list
获取擦干净,每次 good_append
运行?
Why isn't it? What concept am I missing? How does a_list
get wiped clean every time good_append
runs?
推荐答案
的a_list
的默认值(或任何其他的默认值,对于这个问题)存储在函数的内饰一旦被初始化,从而可以以任何方式进行修改:
The default value of a_list
(or any other default value, for that matter) is stored in the function's interiors once it has been initialized and thus can be modified in any way:
>>> def f(x=[]): return x
...
>>> f.func_defaults
([],)
>>> f.func_defaults[0] is f()
因此,在 func_defaults
的值是其内部功能以及已知的(在我例如为了从外部访问它。返回的相同
So the value in func_defaults
is the same which is as well known inside function (and returned in my example in order to access it from outside.
IOW,打电话时会发生什么 F()
是一个隐含的 X = f.func_defaults [0]
。如果该对象随后被修改,你会保持这种修改。
IOW, what happens when calling f()
is an implicit x = f.func_defaults[0]
. If that object is modified subsequently, you'll keep that modification.
在此相反,分配的在的函数总是一个新的 []
得到。任何修改将持续到最后一个引用到 []
已经;在下一个函数调用,一个新的 []
创建
In contrast, an assignment inside the function gets always a new []
. Any modification will last until the last reference to that []
has gone; on the next function call, a new []
is created.
IOW再次,它是不正确的 []
获得在每次执行同一个对象,但它(在默认参数的情况下)只执行一次,然后preserved。
IOW again, it is not true that []
gets the same object on every execution, but it is (in the case of default argument) only executed once and then preserved.
这篇关于为什么采用无固定Python的可变默认参数的问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!