Python 中带有列表附加的可选参数
可能的重复:
Python 中的“最不令人惊讶”:可变默认参数 < /p>
很奇怪,当使用 .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”?我知道它是本地作用域,因为我无法在函数外部访问它,但函数会记住它的值。
Possible Duplicate:
“Least Astonishment” in Python: The Mutable Default Argument
This is very odd, an optional list parameter in Python is persistent between function calls when using the .append() method.
def wtf(some, thing, fields=[]):
print fields
if len(fields) == 0:
fields.append('hey');
print some, thing, fields
wtf('some', 'thing')
wtf('some', 'thing')
The output:
[]
some thing ['hey']
['hey'] # This should not happen unless the fields value was kept
some thing ['hey']
Why does the "fields" list contain "hey" when it is a parameter? I know it's local scope because I can't access it outside the function, yet the function remembers its value.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
默认值仅计算一次,因此使用可变类型作为默认值将产生意外的结果。你最好这样做:
Default values are only evaluated once, so using a mutable type as a default value will produce unexpected results. You'd do better to do something like this: