Error - Default argument is mutable

2015-03-08 21:54:55 +08:00
 jacklong

import doctest

def foo(bar=[]):
"""Error: Default argument is mutable.

Default argument values are evaluated only once at function definition time,
which means that modifying the default value of the argument will affect
all subsequent calls of the function.

>>> foo()
['baz']
>>> foo()
['baz', 'baz']
>>> foo()
['baz', 'baz', 'baz']
"""
bar.append("baz")
print bar

doctest.testmod()

2853 次点击
所在节点    Python
4 条回复
jacklong
2015-03-08 21:56:33 +08:00
代码粘贴进来空格没了,如何缩进?
tkliuxing
2015-03-08 22:45:08 +08:00
@jacklong 在这里贴代码一般用gist
还有,你的主题要表达什么呢?
dddd
2015-03-08 23:23:26 +08:00
默认参数值是可变对象

可以这样:
def foo(bar=None):
if bar is None:
bar = []

看这里……
http://effbot.org/zone/default-values.htm
dant
2015-03-08 23:29:25 +08:00
默认参数指向的对象在定义函数的时候就创建了

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.fyfyfm.apispeedy.workers.dev/t/175394

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX