020函数:内嵌函数和闭包
1.修改函数体内的全局变量的值的方法——global关键字当在函数体内对全局变量修改时,程序会自动生成一个和全局变量名一样的局部变量,但是由于作用域的不同,仍是无法改变全局变量的值,从而保护全局变量;如果实在想改变全局变量就要用到global关键字;
>>> count = 5
>>> def MyFun():
count = 10
print(10)
>>> MyFun()
10
>>> print(count)
5
>>> def MyFun():
global count
count = 10
print(10)
>>> MyFun()
10
>>> print(count)
10
2.内嵌函数(又称内部函数)——简单的说就是函数中的函数
允许在函数内部创建另一个函数这种函数就是内嵌函数
>>> def fun1():
print('fun1()正在被调用...')
def fun2():
print('fun2()正在被调用...')
fun2()
>>> fun1()
fun1()正在被调用...
fun2()正在被调用...
>>> fun2()
Traceback (most recent call last):
File "<pyshell#23>", line 1, in <module>
fun2()
NameError: name 'fun2' is not defined
3.闭包closure
函数是编程重要的语法结构,一种编程的放失;不同的编程语言实现闭包的方式不同;
Python中闭包从表现形式上定义为:如果在一个内部函数里对外部作用域(但不是在全局作用域)的变量进行引用,内部函数就被认为是闭包;
>>> def FunX(x):
def FunY(y):#这里的FunY()就是一个闭包
return x * y
return FunY #直接返回闭包函数名
>>> i = FunX(8) #返回过来的是一个函数对象赋值给 i
>>> i
<function FunX.<locals>.FunY at 0x025B6A98>
>>> type(i)
<class 'function'>
>>> i(5) # i 可以直接进行函数调用
40
>>> FunX(8)(5) #此种形式同样可进行调用
40
>>> FunY(5) #闭包无法直接调用
Traceback (most recent call last):
File "<pyshell#36>", line 1, in <module>
FunY(5)
NameError: name 'FunY' is not defined
4.在内嵌函数内修改外部函数内定义的变量值的方法——nonlocal
>>> def Fun1():
x = 5
def Fun2():
x *= x
return x
return Fun2()
>>> Fun1()
Traceback (most recent call last):
File "<pyshell#44>", line 1, in <module>
Fun1()
File "<pyshell#43>", line 6, in Fun1
return Fun2()
File "<pyshell#43>", line 4, in Fun2
x *= x
UnboundLocalError: local variable 'x' referenced before assignment
改造代码
>>> def Fun1():
x =
def Fun2():
x *= x
return x
return Fun2()
>>> Fun1()
25
使用nonlocal
>>> def Fun1():
x = 5
def Fun2():
nonlocal x
x *= x
return x
return Fun2()
>>> Fun1()
25
页:
[1]