- 1.1
- def outer():
- a = 1
- def inner():
- print(a)
- a += 1
- print('inner')
- inner()
- outer()
内部函数可以使用外部函数的变量.
- # python3
- nonlocal
1.2 闭包:
嵌套的函数, 内部函数调用外部函数的变量.
- 1.2.1
- def outer():
- a = 1
- def inner():
- print(a)
- print(inner.__closure__)
- return inner
- outer()
1.2.2 内部函数可以引用外部函数的变量
- def outer():
- a = 1
- def inner():
- print(a)
- return inner
- outer()
在函数的外部去使用内部的函数;
1.2.3 闭包应用
- from urllib.request import urlopen
- def get_url():
- url = 'http://www.baidu.com'
- def get():
- ret = urlopen(url).read().decode('utf8')
- print(ret)
- return get
- get_func = get_url()
- get_func()
来源: http://www.bubuko.com/infodetail-3394793.html