See this section of code:
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
Official documents are explained here: Default args is evaluated at the time of definition, only once
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)...
Don't say anything, add an ID () output B's so-called address, you understand
No, def foo (a=[]) This function parameter is called the default value of the parameter, only once the function declaration is initialized. And then it won't change any more.
Note, it is recommended to 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 subtle differences between this def foo (*args, **kargs) and this foo (*args, **kargs). No, the default values are shared, created only once, and do not create a new object every time. This means that using a Mutable object as the default value of a function can cause confusion in the function. Similarly, using a dictionary as the default parameter results in a similar return.
deffoo(k,v,fdict={}): fdict[k]=v printfdictfoo(1,2)foo(3,4)