You can see the following code: deffoo (a, B []): B. append (a) printb:
def foo(a, b=[]): b.append(a) print b
Reply content:
>>> def foo(bar=[]):... return bar>>> foo.func_name'foo'>>> foo.func_defaults([],)>>> foo() is foo.func_defaults[0]True
The official document explains here: the default args is evaluated only once during definition.
4. More Control Flow Tools
But ......
>>> 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[]>>>
Needless to say, add an id () to output the so-called address of B, and you will understand.
No, def foo (a = []) is written as the default parameter value, which is initialized only once in the function declaration. It will not change later.
Note: We recommend that you know the difference between def foo (a = []) AND foo (a = []): the former is the default value of the parameter, and the latter is the keyword arguments. there are also some minor differences between def foo (* args, ** kargs) AND foo (* args, ** kargs. No. The default values are shared and will only be created once. No new object will be created each time. that is to say, using a mutable object as the default value of a function can cause confusion. similarly, if you use a dictionary as the default parameter, a similar result is returned.
def foo(k,v, fdict={}): fdict[k] = v print fdictfoo(1,2)foo(3,4)