闭包

闭包 :嵌套函数,内部函数调用外部函数的变量。

 1 a,
 2 def outer():
 3       a = 1
 4     def inner():
 5         print(a)
 6     inner()
 7 outer()
 8 #闭包可以'保护'  a = 1, 在调用函数outer()时不用一直执行并’杀死‘ a = 1     ps,话在嘴边不会描述了,,先这么理解吧。。
 9 b,
10 def outer():
11     a= 1
12     def inner():
13         print(a)
14     return inner
15 inn = outer
16 inn()
17 
18 #outer 是这个函数的地址,”inn = outer“这两个对象都指向outer的地址,outer()是函数的执行。
初见小爬虫:
 1 # import urllib  #模块
 2 from urllib.request import urlopen
 3 # ret = urlopen('http://www.xiaohua100.cn/index.html').read()
 4 # print(ret)
 5 # def get_url():
 6 #     url = 'http://www.xiaohua100.cn/index.html'
 7 #     ret = urlopen(url).read()
 8 #     print(ret)
 9 #
10 # get_url()
11 def get_url():
12     url = 'http://www.xiaohua100.cn/index.html'
13     def get():
14         ret = urlopen(url).read()
15         print(ret)
16     return get
17 
18 get_func = get_url()
19 get_func()

 

 

 

posted @ 2017-12-28 00:41  Carol-z  阅读(117)  评论(0)    收藏  举报