闭包

# closure:闭包
# 闭包:定义在函数内部的函数,这个内部的函数就是闭包

# 应用场景:
# 1.可以去使用其他函数的内部变量,且还可以保证调用位置不变(闭包的函数对象作为那个函数的返回值)
def outer():
count = 3000
def fn():
print(count) # 能使用outer内部的变量count
return fn
# 还是在外界调用
outer()() # outer()() => fn() => 调用fn

# 2.延迟执行(外层函数可以为内存函数传递参数)
import requests

# def show_html(url):
# response = requests.get(url)
# print(response.text)
#
# show_html('https://www.baidu.com')
# show_html('https://www.baidu.com')
# show_html('https://www.sina.com.cn')

def outer(url):
def show_html():
response = requests.get(url)
print(response.text)
return show_html
# 制作 爬百度与新浪的 函数对象
show_baidu = outer('https://www.baidu.com')
show_sina = outer('https://www.sina.com.cn')
# 延迟到需求来了,需要爬百度,就用百度函数对象,需要爬新浪,就用新浪函数对象
show_baidu()
show_sina()
show_baidu()
原文地址:https://www.cnblogs.com/qiangyuzhou/p/10787405.html