python inline functions and closures

0. To modify the value of a global variable in a function, the global keyword should be used

>>> num = 1
>>> def FunA():
global num
num = 5
print(num)>>> FunA()5>>> 



1. In the embedded function, if the internal function modifies the local variables of the external function, the nonlocal keyword should be used

Before there is no nonlocal, access and modify the internal function by assigning the variable as a list to the container type

>>> def FunB():

x=[1]
def FunC():
x[0] +=1
return x[0]
return FunC()
>>> FunB()

2

Use the nonlocal keyword

>>> def FunB():
x=1
def FunC():
nonlocal x
x +=1
return x
return FunC()


>>> FunB()
2

2. Closures: functional programming.

def FunA(x):

    def FunB(y):

         return x*y

    return FunB



Guess you like

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