python 内嵌函数与闭包

0.在函数中修改全局变量的值,应该使用global关键字

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

1. 在内嵌函数中,如果在内部函数修改外部函数的局部变量,应该用nonlocal关键字

在没有nonlocal之前,通过将变量赋值为列表变为容器类型在内部函数进行访问修改

>>> def FunB():

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

2

利用nonlocal关键字

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


>>> FunB()
2

2.闭包:函数式编程。

def FunA(x):

    def FunB(y):

         return x*y

    return FunB



猜你喜欢

转载自blog.csdn.net/dxcve/article/details/80039541