import random
import time
# 装饰器函数的参数也是一个函数,它代表了被装饰的函数
# 装饰器函数的返回值也是一个函数,它代表了带有装饰功能的函数
def record_time(func):
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f'消耗时间: {end - start:.3f}秒')
return result
return wrapper
@record_time
def download(filename):
"""下载文件"""
print(f'开始下载{filename}.')
time.sleep(2 + random.random() * 5)
print(f'{filename}下载完成.')
@record_time
def upload(filename):
"""上传文件"""
print(f'开始上传{filename}.')
time.sleep(3 + random.random() * 6)
print(f'{filename}上传完成.')
# download = record_time(download)
# upload = record_time(upload)
download('MySQL从删库到跑路.avi')
upload('Python从入门到住院.pdf')35.装饰器
本节843字2025-05-13 10:16:45