一、什么是装饰器
装饰器:
- 不修改被装饰对象的源代码
- 不修改被装饰对象的调用方式
import time
# 初级下载版
def download_movie():
print('开始下载电影...')
time.sleep(3)
print('电影下载成功...')
start_time = time.time()
print(time.time())
download_move()
end_time = time.time()
print(time.time())
print(f'消耗时间:{start_time - end_time}')
# 加入计时函数
def download_movie():
print('开始下载电影....')
time.sleep(3)
print('完成下载电影....')
def time_timer(func):
def timer_inner():
start_time = time.time()
func()
end_time = time.time()
print(f'下载用时:{end_time - start_time}')
return timer_inner
download_movie = time_timer(download_movie)
download_movie()
# 问题1:被装饰对象有返回值
# 下载电影功能
def download_movie():
print('开始下载电影...')
time.sleep(3)
print('下载完毕...')
return '小泽.mp4'
def time_timer(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_timer(download_movie)
download_movie()
# 问题2:被装饰对象 有参数
def download_movie():
print('下载开始....')
time.sleep(3)
print('下载完成')
return '小泽.mp4'
def time_timer(func):
def timer_inner(*args, **kwargs):
start_time = time.time()
res = func(*args, **kwargs)
end_time = time.time()
print(f'耗费时间:{end_time - start_time}')
return res
return timer_inner
download_movie = time_timer(download_movie)
download_movie()
# 二、装饰器的模板
模板:
def outer(func):
def inner(*args,**kwargs):
res=func(*args,**kwargs)
return res
return inner