什么是闭包?
如果一个函数里面定义了另外一个函数,里面定义的函数使用了外面函数中定义的变量,并且外面的函数返回了里面的函数的引用,那么称里面的函数为闭包。如下面代码中hello函数就是一个闭包。
def greet1(name):
print('outter')
def hello():
print('hello,my name is %s' % name)
return hello
func1 = greet1('liming')
#打印outter,func1拿到hello函数的引用
func1()
#打印hello,my name is liming
nonlocal关键字
如果想要在闭包中修改外面函数中的变量,则应该在闭包中使用nonlocal关键字对变量进行标识。
def greet2(name: object) -> object:
print('outter name is %s' % name)
def say_hello():
nonlocal name
name += 'liu'
print('innner name is %s' % name)
return say_hello
greet2('liming')()
#utter name is liming
#innner name is limingliu
小实例:使用闭包实现y=2x+1和y=2x+2两个算式的值
def func(option):
"""
使用option选择需要初始化的函数
func1为y=2x+1
func2为y=2x+2
"""
if option == 1:
def func1(x):
return 2*x+1
return func1
elif option == 2:
def func2(x):
return 2*x+2
return func2
else:
print("error")
print(func(1)(2))
#得到结果:5
print(func(2)(2))
#得到结果:6