首页 > 代码库 > 高级闭包用法

高级闭包用法

高级闭包用法:

#!/usr/bin/env python# !-*-coding:utf-8-*-"""高级装饰器和闭包实例"""import timedef logged(when):    """    输出函数的日志信息    :param when: 选取那种日志格式    """    def log(f, *args, **kargs):        print "asdfads %s" %f        print """ Called:        function:%s        args:        kargs        """  % f    def pre_logged(f):        def wrapper(*args, **kwargs):            log(f, *args, **kwargs)            try:                return f(*args, **kwargs)            except Exception, e:                print e        return wrapper    def post_logged(f):        print f        def wrapper(*args, **kwargs):            log(f, *args, **kwargs)            try:                now = time.time()                return f(*args, **kwargs)            except Exception, e:                print e            finally:                print "time waster: %d" % (time.time()-now)        return wrapper    return {"pre": pre_logged,            "post": post_logged}[when]@logged("post")def func(aa):    print aafunc("打倒日本帝国主义")

 

高级闭包用法