1、请设计一个decorator,它可作用于任何函数上,要求可以接收一个int作为参数,如果该函数的执行时间大于int传递的时间话,请打印该函数名字和执行时间
import datetime
import time
def decorator_time(time):
def decorator(func):
def print_time(*args,**kwargs):
exec_start_time = datetime.datetime.now()
func(*args,**kwargs)
exec_end_time = datetime.datetime.now()
exec_time = (exec_end_time-exec_start_time).seconds
if exec_time > int(time):
print("函数名称",func.__name__)
print (f"执行时间:{exec_time}")
return print_time
return decorator
@decorator_time(1)
def test_1():
time.sleep(2)
print("sleep 2")
test_1()
代码解释:
1. 因为需要接收参数,故装饰器要写3个函数嵌套,首先定义3个函数
def decorator_time(time): # def decorator_time(time):中的参数time,是定义接收的参数;
def decorator(func): # 定义接收要执行的函数例如test1
def print_time(*args,**kwargs): # *args,**kwargs 接收执行函数test1()中的参数
# 代码
return print_time
return decorator
2. 然后在print_time编写需要执行的逻辑代码