closure of python function

  • definition:

Two nested functions, the inner function references the variables or parameters of the outer layer, and the outer function returns the inner function (not only returns the inner function, but also stores the part of the variable referenced by the inner function in the inner layer) In the function, it returns with the inner function)

  • Code

#define a sum function, don't sum immediately, sum again when called 
def sumF(*args): 
    def f(): 
        result = 0 
        for i in args: 
            result += i 
        return print(result) 

    return f 

# function call 
sum = sumF(1, 2, 3, 4, 5) 
and ()

  • Precautions

The outer variable cannot be modified in the inner function. If you have to modify it, add a non-local in front of the variable

  • E.g

    

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325892074&siteId=291194637