时间:2021-07-01 10:21:17 帮助过:70人阅读
def foo(a, b=[]): b.append(a) print b
>>> def foo(bar=[]):
... return bar
>>> foo.func_name
'foo'
>>> foo.func_defaults
([],)
>>> foo() is foo.func_defaults[0]
True
官方文档解释在这里:default args 的求值是在定义的时候,只做一次>>> def f(a, b=[]):
... b.append(a)
... print b
...
>>> f(1)
[1]
>>> f(1)
[1, 1]
>>> def f(a, b=None):
... b = b if b is not None else []
... b.append(a)
... print b
...
>>> f(1)
[1]
>>> f(1)
[1]
>>> f(1)
[1]
>>> a = []
>>> b = []
>>> a.append(1)
>>> b
[]
>>>
啥都不用说,加一个id()输出b的所谓的地址,你就明白了def foo(k,v, fdict={}):
fdict[k] = v
print fdict
foo(1,2)
foo(3,4)