
---恢复内容开始---
python允许有内部函数,也就是说可以在函数内部再定义一个函数,这就会产生变量的访问问题,类似与java的内部类,在java里内部类可以直接访问外部类的成员变量和方法,不管是否私有,但外部类需要通过内部类的引用来进行访问。python内部函数和外部函数的成员变量可以相互访问但是不能修改,也就是所谓的闭包。举个例子
def outt():
x=10
def inn():
x+=1
return x
return inn() outt()
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "<input>", line 6, in outt
File "<input>", line 4, in inn
UnboundLocalError: local variable 'x' referenced before assignment
可以使用nonlocal 关键字修饰外部的成员变量使其可以被修改,具体如下
def outt():
x=10
def inn():
nonlocal x
x+=1
return x
return inn() outt()
11
对于传的参数外函数和内函数也是闭包的 举例如下
def outt():
x=10
def inn(y):
nonlocal x
x+=y
return x
return inn(y) outt()(10)
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "<input>", line 7, in outt
NameError: global name 'y' is not defined
但是可以简化写法避免传参问题
def outt():
x=10
def inn(y):
nonlocal x
x+=y
return x
return inn outt()(10)
20
可以看出外函数调用内函数时没有在括号里传参python可以对他进行默认的赋值操作,这样就避免了参数在两个函数之间的传递问题