本质上是函数,用来装饰其他函数,给函数添加新的功能
def timmer(func): def wrapper(*args, **kwargs): start_time = time.time() func(args[0]) end_time = time.time() print(‘fun1 run time is %s‘ %(end_time - start_time)) return wrapper @timmer # 等价于:fun1 = timmer(fun1), 此时fun1先指向函数1,然后指向新的函数wrapper def fun1(a): time.sleep(3, a) print(‘fun1...‘) if __name__ == ‘__main__‘: fun1(10) # 装饰器的实现原理: fun1 = timmer(fun1); fun1(10)
本质上将函数指向新的函数地址。
嵌套函数的参数就是源函数的参数。
def timmer(func): def wrapper(*args, **kwargs): start_time = time.time() result = func(*args, **kwargs) end_time = time.time() print(‘fun1 run time is %s‘ %(end_time - start_time))
return result return wrapper @timmer # 等价于:fun1 = timmer(fun1), 此时fun1先指向函数1,然后指向新的函数wrapper def fun1(a): time.sleep(3, a) print(‘fun1...‘) if __name__ == ‘__main__‘: fun1(10) # 装饰器的实现原理: fun1 = timmer(fun1); fun1(10)
@timmer(param = ‘‘)
import time def timmer(param): print(param) def out_wrapper(func): def wrapper(*args, **kwargs): start_time = time.time() result = func(*args, **kwargs) end_time = time.time() print(‘fun1 run time is %s‘ % (end_time - start_time)) return result return wrapper return out_wrapper @timmer(param=‘decorator param‘) # fun1 = timmer(fun1) def fun1(a,*b): print(‘fun1...‘, a, b) if __name__ == ‘__main__‘: fun1(10, 20, 20)
原文:https://www.cnblogs.com/zhuxiang1633/p/9310741.html