|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
内嵌函数和闭包内嵌函数:在函数内部创建另一个函数 - >>> def fun1():
- print('fun1() is running...')
- def fun2():
- print('fun2() is running...')
- fun2()
- >>> fun1()
- fun1() is running...
- fun2() is running...
复制代码
内部函数的整个作用域都在外部函数之内 闭包:在一个内部函数里,对外部作用域(但不是在全局作用域)的变量进行引用,内部函数就会被认为是闭包 - >>> def funx(x):
- def funy(y):
- return x*y
- return funy
- >>> i = funx(8)
- >>> type(i)
- <class 'function'>
- >>> i(5)
- 40
- >>> funx(8)(5)
- 40
复制代码在内部函数funy()中,对外部作用域(但不是全局作用域)的变量x进行引用,则funy()构成闭包 列表不存放在栈里面,可以再外部函数和内部(嵌)函数之间进行数据交换、赋值、修改 - >>> def fun1():
- x = 5
- def fun2():
- x *= x
- return x
- return fun2()
- >>> fun1()
- Traceback (most recent call last):
- File "<pyshell#26>", line 1, in <module>
- fun1()
- File "<pyshell#25>", line 6, in fun1
- return fun2()
- File "<pyshell#25>", line 4, in fun2
- x *= x
- UnboundLocalError: local variable 'x' referenced before assignment
- >>> def fun1():
- x = [5]
- def fun2():
- x[0] *= x[0]
- return x[0]
- return fun2()
- >>> fun1()
- 25
复制代码
也可以用nonlocal关键字声明非局部变量,从而修改外部变量值 - >>> def fun1():
- x = 5
- def fun2():
- nonlocal x
- x *= x
- return x
- return fun2()
- >>> fun1()
- 25
复制代码
|
评分
-
查看全部评分
|