闭包函数+装饰器(第十一天)
闭包函数是,函数嵌套、函数对象、名称空间和作用域的结合体
# 直接传参
# def func(x):
# print(x)
#
# func(100)
# 通过闭包函数传参
# def foo(num):
# num = 100
# def coo():
# print(num)
# return coo
# func = foo(1000)
# func()
闭包函数的应用
了解:为了装饰器准备
下载:pip3 install requests
使用:import requests
需求:爬取某个网站,打印获取数据的长度
# 直接传参
import requests
# def sp_fu(url):
# response = requests.get(url)
# if response.status_code == 200:
# print(len(response.text))
# print(response.text)
# url = 'https://www.cnblogs.com/xiaoyuanqujing/'
# sp_fu(url)
# def spider_outer(url):
# # url = 'https://www.cnblogs.com/xiaoyuanqujing/'
# def spider_inner():
# response = requests.get(url)
# if response.status_code == 200:
# print(len(response.text))
# return spider_inner
#
# spider_blog = spider_outer('https://www.cnblogs.com/xiaoyuanqujing/')
# spider_blog()
装饰器*
'''
需求:统计下载电影的时间
装饰器:
不能修改被装饰对象的源代码
不修改被装饰对象的调用方式
被装饰对象:--->需要添加功能 的函数
装饰器:--->被装饰对象添加新功能的函数
'''
# import time
# def download_movie():
# print('开始下载电影...')
# # 模拟电影下载时间 3秒
# time.sleep(3) # 等待3秒
# print('电影下载成功...')
#
# def time_record(func):
# def inner():
# start_time = time.time()
# func()
# end_time = time.time()
# print(f'消耗时间:{end_time - start_time}'')
# # return inner
# download_movie = time_record(download_movie)
# download_movie()
# 被装饰对象有返回值
# def download_movie():
# print('开始下载电影...')
# # 模拟电影下载时间 3秒
# time.sleep(3) # 等待3秒
# print('电影下载成功...')
# return '小泽.mp4'
# def foo():
# a = download_movie()
# return a
# print(download_movie())
# def time_record(func):
# def inner():
# start_time = time.time()
# res = func()
# end_time = time.time()
# print(f'消耗的时间:{end_time - start_time}')
# return res
# return inner
# download_movie = time_record(download_movie)
# download_movie()
# 被装饰对象有参数
# def download_movie(url):
# print(f'{url}中的电影开始下载了...')
# 模拟电影下载时间 3秒
# time.sleep(3) # 等待3秒
# print('电影下载成功...')
# return '小泽.mp4'
# def time_record(func): # func <-- download_movie
# # # url = 'https://www.baidu.com/'
#
# # 在闭包函数中
# def inner(url):
# # 统计开始
# start_time = time.time()
# res = func(url) # func(url) ---> download_movie(url)
# # 当被统计的函数执行完毕后,获取当前时间
# end_time = time.time()
# # 统计结束,打印统计时间
# print(f'消耗时间: {end_time - start_time}')
# return res
# return inner
#
#
# download_movie = time_record(download_movie)
#
# # download_movie(url) --> inner(url)
# download_movie('https://www.baidu.com')
#
# def download_movie2(*args,**kwargs):
# print(f'{url}中的电影开始下载了...')
# # 模拟电影下载时间 3秒
# time.sleep(3) # 等待3秒
# print('电影下载成功...')
# return '小泽.mp4'
# def time_record(func): # func <-- download_movie
# # url = 'https://www.baidu.com/'
#
# # 在闭包函数中
# def inner(*args,**kwargs):
# # 统计开始
# start_time = time.time()
#
# res = func(*args,**kwargs) # func(url) ---> download_movie(url)
#
# # 当被统计的函数执行完毕后,获取当前时间
# end_time = time.time()
# # 统计结束,打印统计时间
# print(f'消耗时间: {end_time - start_time}')
# return res
# return inner
#
#
# download_movie = time_record(download_movie)
#
# # download_movie(url) --> inner(url)
# download_movie('https://www.baidu.com')