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()
1
jacklong OP 代码粘贴进来空格没了,如何缩进?
|
3
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 |
4
dant 2015-03-08 23:29:25 +08:00 via iPhone
默认参数指向的对象在定义函数的时候就创建了
|