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

 

posted @ 2013-10-18 18:00  Ice_Max  阅读(155)  评论(0编辑  收藏  举报