This is covered in detail in a relatively popular SO question, but I'll try to explain the issue in your particular context.
When your declare your function, the default parameters get evaluated at that moment. It does not refresh every time you call the function.
The reason why your functions behave differently is because you are treating them differently. In f1
you are mutating the object, while in f2
you are creating a new integer object and assigning it into b
. You are not modifying b
here, you are reassigning it. It is a different object now. In f1
, you keep the same object around.
Consider an alternative function:
def f3(a, l= []):
l = l + [a]
return l
This behaves like f2
and doesn't keep appending to the default list. This is because it is creating a new l
without ever modifying the object in the default parameter.
Common style in python is to assign the default parameter of None
, then assign a new list. This gets around this whole ambiguity.
def f1(a, l = None):
if l is None:
l = []
l.append(a)
return l
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…