一、内嵌函数&闭包
1、最好是访问全局变量而不是修改全局变量,修改全局变量Python会内部屏蔽(修改后,函数会内部创建一个和全局变量一抹一样的变量)
>>> count = 5
>>> def MyFun():
count = 10
print(10)
>>> MyFun()
10
>>> print(count)
5
>>>
---外部先定义了一个count的全局变量,然后MyFun()内部对count进行了修改,打印MyFun()函数发现,是修改后的count,但是在打印count变量,仍然是全局变量的值5,这说明函数内对全局变量的修改,会直接被屏蔽
2、global关键字(可以用global关键字进行修改)
>>> count =5
>>> def MyFun():
global count
count = 10
print(10)
>>> MyFun()
10
>>> print(count)
10
>>>
3、内嵌函数(内部函数):函数内部创建另外一个函数
>>> def fun1():
print('fun1正在被调用!')
def fun2():
print('fun2正在被调用!')
fun2()
>>> fun1()
fun1正在被调用!
fun2正在被调用!
4、闭包:
def FunX(x):
def FunY(y):
return x*y
return FunY
>>> FunX(8)(5)
40
>>> i = FunX(8)
>>> i
<function FunX.<locals>.FunY at 0x10598b400>
>>> i(5)
40
---闭包满足的两个条件:a、首先FunY是FunX的内部函数,并且FunY引用FunX的整个作用域 b、FunY引用FunX的变量x
---闭包的基本形式:
在函数FunX中,定义FunY,FunY只能引用FunX定义的变量,之后FunX函数返回FunY函数的名字
>>> def fun1():
x = 5
def fun2():
x *=x
return x
return fun2()
>>> fun1()
Traceback (most recent call last):
File "<pyshell#75>", line 1, in <module>
fun1()
File "<pyshell#74>", line 6, in fun1
return fun2()
File "<pyshell#74>", line 4, in fun2
x *=x
UnboundLocalError: local variable 'x' referenced before assignment
>>>
---报错的原因:(UnboundLocalError: local variable 'x' referenced before assignment)UnboundLocalError:赋值之前引用的局部变量'x',即:x是个局部变量,fun2赋值的时候x已经被屏蔽了,所以没办法引用
---解决方式:
A、采用数组这样的容器
>>> def fun1():
x = [5]
def fun2():
x[0] *=x[0]
return x[0]
return fun2()
>>> fun1()
25
B、采用nonlocal关键字,强制声明x不是一个局部变量
>>> def fun1():
x = 5
def fun2():
nonlocal x
x *=x
return x
return fun2()
>>> fun1()
25
二、练习题
1、闭包举例:
def fun1():
x = 5
def fun2():
nonlocal x
x +=1
return x
return fun2
a = fun1()
print(a())
print(a())
print(a())
'''执行结果:
6
7
8 '''