在函数嵌套的前提下,内层函数引用了外层函数的变量(包括参数),外层函数,又把内层函数,当做返回值进行返回,内层函数所引用外层变量称为闭包。
def test():
a = 10
def test2():
print(a)
return test2
newFunc = test()
newFunc()
10
应用场景:外层函数,根据不同的参数,来生成不同作用功能的函数。
def line_config(content, length):
def line():
print('-' * (length // 2) + content + '-' * (length // 2))
return line
line1 = line_config('闭包', 40)
line1()
line2 = line_config('xxx', 80)
line2()
--------------------闭包--------------------
----------------------------------------xxx----------------------------------------
- 闭包中,如果要修改引用的外部变量,需要用nonlocal 变量声明,否则当作是闭包内,新定义的变量。
def test():
num = 10
def test2():
nonlocal num
num = 666
print(num)
print(num)
test2()
print(num)
return test2
result = test()
10
666
666
- 当闭包内,引用了一个,后期会发生变化的变量时,一定要注意,当函数被调用的时候,才会真正的确定对应的值,之前都是以普通的变量标识名称而存在。
def test():
a = 1
def test2():
print(a)
a = 2
return test2
newFunc = test()
newFunc()
2
def test():
funcs = []
for i in range(1, 4):
def test2():
print(i)
funcs.append(test2)
return funcs
newFuncs = test()
print(newFuncs)
newFuncs[0]()
newFuncs[1]()
newFuncs[2]()
[<function test..test2 at 0x044006F0>, <function test..test2 at 0x04400738>, <function test..test2 at 0x04400780>]
3
3
3
def test():
funcs = []
for i in range(1, 4):
def test2(num):
def inner():
print(num)
return inner
funcs.append(test2(i))
return funcs
newFuncs = test()
print(newFuncs)
newFuncs[0]()
newFuncs[1]()
newFuncs[2]()
[<function test..test2..inner at 0x03C70780>, <function test..test2..inner at 0x03C70738>, <function test..test2..inner at 0x03C707C8>]
1
2
3