【发布时间】:2011-10-15 06:07:27
【问题描述】:
可能重复:
“Least Astonishment” in Python: The Mutable Default Argument
这很奇怪,当使用 .append() 方法时,Python 中的可选列表参数在函数调用之间是持久的。
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']
为什么“fields”列表作为参数时包含“hey”?我知道它是本地作用域,因为我无法在函数之外访问它,但函数会记住它的值。
【问题讨论】:
标签: python optional-parameters