When defining the default parameters of the python function, why do you use immutable objects to avoid the problems caused by mutable objects?

def test(def_arg=None):
    if def_arg == None:
        def_arg = []
    def_arg.append(1)
    return def_arg

test()
test()

when the test function is called for the first time, def_arg is assigned to the value of none when the function is defined, so def_arg is bound to a list object, and then an item is added.

Why is the value of def_arg still None instead of [1] when the test function is called for the second time?

Feb.12,2022

def add_end(L=[]):
    L.append('END')
    return L
When the

Python function is defined, the value of the default parameter L is calculated, that is, [], because the default parameter L is also a variable, which points to the object []. Each time the function is called, if the content of L is changed, the content of the default parameter will be changed the next time it is called, and it is no longer the [] as it was when the function was defined.


def test(def_arg=None):

None is the default parameter, def_arg is not.

so changing def_arg will not change the default parameters, but changing None will. But None is immutable, so the default parameters never change.

but

def test(def_arg=[]):

def_arg.append changes the default parameter [] . So the default parameters will change when called again.


_

example:

def f(n,ls=5):
    ls +=1
    return n+ls
print(f(1))        -sharp7
print(f(2))        -sharp8
Is it possible that

is an object in which the default parameter of the formal parameter belongs to f, which exists with the existence of f, and ls + = 1 is temporarily bound in the variable space that exists when the function is called, that is, this ls and the formal parameter ls are not the same thing?

(one is in the f. Variables defaultsspace _, and the other is in the variable space temporarily generated by the call)

Menu