函数内嵌指一个函数内部包含定义另一个函数
举例:
def fun1():
print('fun1()正在被调用...')
def fun2():
print('fun2()正在被调用...')
fun2()
fun1()
fun1()正在被调用...
fun2()正在被调用...
fun2()
Traceback (most recent call last):
File "", line 1, in
fun2()
NameError: name 'fun2' is not defined
闭包(closure)是函数式编程的一个重要的语法结构,函数式编程是一种编程范式,著名的函数式编程语言就是LISP语言.
Python中的闭包从表现形式上定义为:如果在一个内部函数里,对在外部作用域(但不是在全局作用域)的变量进行引用,那么内部函数就是被认为闭包.
举例
def FunX(x):
def FunY(y): //FunY就是FunX的内部函数,FunX的整个函数作用域为FunY的外部作用域,变量x
return x * y
return FunY
i = FunX(8)
i //i是一个function
.FunY at 0x029CDCD8>
type(i)
i(5)
40
FunX(8)(5)
40
FunY(5)
Traceback (most recent call last):
File "", line 1, in
FunY(5)
NameError: name 'FunY' is not defined
内部函数对外部函数的局部变量只能进行引用,不能进行修改
举例:
def Fun1():
x = 5
def Fun2():
x *= x //x为外部函数的局部变量,只能引用不能修改
return x
return Fun2()
Fun1()
Traceback (most recent call last):
File "", line 1, in
Fun1()
File "", line 6, in Fun1
return Fun2()
File "", line 4, in Fun2
x *= x
UnboundLocalError: local variable 'x' referenced before assignment
解决办法
方法一:
容器类型存放解决,容器类型不是存放在栈中
def Fun1():
x = [5] //用列表来存放x
def Fun2():
x[0] *= x[0]
return x[0]
return Fun2()
Fun1()
25
方法二
nonlocal关键字,3.0以后版本加入
def Fun1():
x = 5
def Fun2():
nonlocal x
x *= x
return x
return Fun2()
Fun1()
25