玩蛇网提供最新Python编程技术信息以及Python资源下载!

Python装饰器日志方法的简单实现

'''
Created on 2011-3-23
www.iplaypy.com

'''
from time import time

def logged (when):
    def log(f,*args,**kargs):
        print('''called: 
        function: %s 
        args :%r 
        kargs:%r''' %(f,args,kargs))
        
    def pre_logged(f):
        def wrapper(*args,**kargs):
            log(f,*args,**kargs)
            print('in pre_logged')
            return f(*args,**kargs)
        return wrapper
    
    def post_logged(f):
        def wrapper(*args,**kargs):
            print('in post_logged *')
            now =time()
            try:
                return f(*args,**kargs)
            finally:
                log(f,*args,**kargs)
                print('time delta: %s' % (time()-now))
                print('in post_logged')
        return wrapper
    
    try:
        return {"pre":pre_logged,"post":post_logged}[when]
    except KeyError as e:
        raise ValueError(e)('must be "pre" or "post" ')
    
@logged('pre')    
@logged('post')
def hello(name):
    print('hello, ',name)


hello('world!')

玩蛇网文章,转载请注明出处和文章网址:https://www.iplaypy.com/code/other/o2487.html

相关文章 Recommend

玩蛇网Python互助QQ群,欢迎加入-->: 106381465 玩蛇网Python新手群
修订日期:2016年03月30日 - 11时41分51秒 发布自玩蛇网

您现在的位置: 玩蛇网首页 > Python源码实例 > 其它Python源码 > 正文内容
我要分享到:

必知PYTHON教程 Must Know PYTHON Tutorials

必知PYTHON模块 Must Know PYTHON Modules