|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
020函数:内嵌函数和闭包
一、Global关键字
1、屏蔽Shadowing:试图在函数内部修改全局变量时,python会生成一个同名的局部变量,只修改了python创建的局部变量。
- >>> count = 5
- >>> def Myfun():
- count = 10
- print(10)
-
- >>> Myfun()
- 10
- >>> print(count)
- 5
复制代码
2、运用global修改全局变量
- >>> def Myfun():
- global count
- count = 10
- print(10)
-
- >>> Myfun()
- 10
- >>> print(count)
- 10
复制代码
二、内嵌函数(内部函数)
- >>> def fun1():
- print('fun1()正在被调用...')
- def fun2():
- print('fun2()正在被调用...')
- fun2()
-
- >>> fun1()
- fun1()正在被调用...
- fun2()正在被调用...
- >>> fun2()
- Traceback (most recent call last):
- File "<pyshell#33>", line 1, in <module>
- fun2()
- NameError: name 'fun2' is not defined
复制代码
三、闭包closure
1、闭包:函数式编程的一个重要结构
- >>> def funx(x):
- def funy(y):
- return x * y
- return funy
- >>> i = funx(8)
- >>> i(5)
- 40
- >>> funx(8)(5)
- 40
复制代码
如果在一个内部函数里【funy】,为在外部作用域【funx】的变量【x】,这个内部函数【funy】就是一个闭包。
2、注意
(1)闭包是由内部函数演变而来,不能在外部函数的外边对内部函数进行调用
(2)闭包中外部函数的局部变量对内部函数的局部变量的关系==全局变量对局部变量的关系:即小对大只能访问不能修改
- >>> def fun1():
- x = 5
- def fun2():
- x *= x
- return x
- return fun2()
- >>> fun1()
- Traceback (most recent call last):
- File "<pyshell#58>", line 1, in <module>
- fun1()
- File "<pyshell#57>", line 6, in fun1
- return fun2()
- File "<pyshell#57>", line 4, in fun2
- x *= x
- UnboundLocalError: local variable 'x' referenced before assignment
复制代码
3、内部修改外部函数的局部变量
(1)python2:修改容器类型(列表、元组)
- >>> def fun1():
- x = [5]
- def fun2():
- x[0] *= x[0]
- return x[0]
- return fun2()
- >>> fun1()
- 25
复制代码
(2)python3:运用nonlocal关键字
- >>> def fun1():
- x = 5
- def fun2():
- nonlocal x
- x *= x
- return x
- return fun2()
- >>> fun1()
- 25
复制代码 |
|