Python装饰器示例
曾经有这么一个需求,想要将程序中跑的整个process友好地显示出来,这样子后来者在看log的时候,就能够很清楚地知道程序source code中function的调用逻辑,方便理解。在接触到装饰器之前,以为想要达到这样的目的,就需要在每个function的开始和结束的部分加上相应的code,现在装饰器帮忙解决了这个问题。
#装饰器有许多方法,但最简单和最容易理解的方法是编写一个函数,返回封装原始函数调用的一个子函数 #此处,原始函数为func,子函数为result,最终的装饰器就是decorator def decorator(func): def result(*args, **dic): print "Function --- %s is start" %func.__name__ res = func(*args, **dic) print "Function --- %s is end" %func.__name__ return res return result @decorator def test(): print "This is test" test() ######## 输出结果 ######## Function --- test is start This is test Function --- test is end
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步