-
定义:
-
外部函数中定义一个内部函数,
-
内部函数中使用了外部函数的变量,
-
外部函数将内部函数作为返回值返回。
-
-
示例:
'''
# 这不是闭包
def wai():
def nei():
print('内部函数')
return nei
a = wai()
a()
'''
'''
def wai(n):
def nei():
return n*n
return nei
f1 = wai(3)
f2 = wai(5)
print(f1())
print(f2())
'''
'''
def wai(*args):
def nei():
he = 0
for i in args:
he += i
return he
return nei
f1 = wai(1,2,3)
print(f1())
'''
# y = ax + b
def wai(a, b):
def nei(x):
return a*x + b
return nei
f1 = wai(3, 5)
# f1 <=> y = 3*x + 5
print(f1(3))
f2 = wai(5, 8)
print(f2(6))
print(wai(2,3)(4))
-
作用:提高代码的复用度