python装饰器

来源:互联网 发布:python实现二叉树反转 编辑:程序博客网 时间:2024/06/16 04:43


python装饰器语法有点麻烦,参考http://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/001386819879946007bbf6ad052463ab18034f0254bf355000

# -*- coding:UTF-8 -*-import functoolsdef log(f):    @functools.wraps(f)    def wrapper(*args, **kw):        print 'before call %s():' % f.__name__        result= f(*args, **kw)        print  'after call %s():' % f.__name__        return result    return wrapper# 观察上面的log,因为它是一个decorator,所以接受一个函数作为参数,# 并返回一个函数。我们要借助Python的@语法,把decorator置于函数的定义处:@logdef fun():    print 'fun invoke'    return 'fun result'res=fun()print resprint fun.__name__# 打印如下# before call fun():# fun invoke# after call fun():# fun result# fun# 把@log放到fun()函数的定义处,相当于执行了语句:# fun = log(fun)# # 由于log()是一个decorator,返回一个函数,所以,原来的fun()函数仍然存在,只是现在同名的fun变量指向了新的函数,# 于是调用fun()将执行新函数,即在log()函数中返回的wrapper()函数。# # wrapper()函数的参数定义是(*args, **kw),因此,wrapper()函数可以接受任意参数的调用。# 在wrapper()函数内,首先打印日志,再紧接着调用原始函数。print'////////////////////////////////////////////////////'# 如果decorator本身需要传入参数,那就需要编写一个返回decorator的高阶函数,写出来会更复杂。比如,要自定义log的文本:def log2(text):    def decorator(func):        @functools.wraps(func)        def wrapper(*args, **kw):            print 'before %s %s():' % (text, func.__name__)            result= func(*args, **kw)            print 'after %s %s():' % (text, func.__name__)            return result        return wrapper    return decorator# 这个3层嵌套的decorator用法如下:@log2('execute')def now():    print 'now invoke'    now()print now.__name__# 打印如下# before execute now():# now invoke# after execute now():# now# # 和两层嵌套的decorator相比,3层嵌套的效果是这样的:# # now = log2('execute')(now)# # 我们来剖析上面的语句,首先执行log2('execute'),返回的是decorator函数,再调用返回的函数,参数是now函数,返回值最终是wrapper函数。


0 0