Python - 装饰器
Posted Archibald Witwicky
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python - 装饰器相关的知识,希望对你有一定的参考价值。
import time import functools def exec_time(func): def wrapper(*args, **kw): print(time.strftime(‘%Y-%m-%d %H:%M:%S‘,time.localtime(time.time()))) return func(*args, **kw) return wrapper @exec_time def testfunc(): print("test function...") testfunc() print(testfunc.__name__) print("=====================") def exec_time(text): def deractor(func): @functools.wraps(func) def wrapper(*args, **kw): print(time.strftime(text, time.localtime(time.time()))) return func(*args, **kw) return wrapper return deractor @exec_time(‘%Y-%m-%d‘) def testfunc(): print("test function...") testfunc() print(testfunc.__name__) print("=====================") def exec_time(text): def deractor(func): @functools.wraps(func) def wrapper(*args, **kw): print("begin time:", time.strftime(text, time.localtime(time.time()))) t = func(*args, **kw) print("end time:", time.strftime(text, time.localtime(time.time()))) return t; return wrapper return deractor @exec_time(‘%Y-%m-%d %H:%M:%S‘) def testfunc(): print("test function...") testfunc() print(testfunc.__name__)
output:
2017-12-03 20:50:00 test function... wrapper ===================== 2017-12-03 test function... testfunc ===================== begin time: 2017-12-03 20:50:00 test function... end time: 2017-12-03 20:50:00 testfunc
以上是关于Python - 装饰器的主要内容,如果未能解决你的问题,请参考以下文章