python 的修饰器是一种语法糖(syntactic sugar),也就是说:
@decorator@wrapdef func(): pass
是下面语法的一种简写:
def func(): passfunc = decorator(wrap(func))
关于修饰器的两个主要问题:
修饰器用来修饰谁
谁可以作为修饰器
修饰函数 修饰器最常见的用法是修饰新定义的函数,在 0x0d 上下文管理器中提到上下文管理器主要是为了 更优雅地完成善后工作,而修饰器通常用于扩展函数的行为或属性:
def log(func): def wraper(): print(info: starting {}.format(func.__name__)) func() print(info: finishing {}.format(func.__name__)) return wraper@logdef run(): print(running run...)run()
info: starting runrunning run...info: finishing run
修饰类 除了修饰函数之外,python 3.0 之后增加了对新定义类的修饰(pep 3129),但是对于类别属性的修改可以通过 metaclasses或继承来实现,而新增加的类别修饰器更多是出于 jython 以及 ironpython 的考虑,但其语法还是很一致的:
from time import sleep, timedef timer(cls): def wraper(): s = time() obj = cls() e = time() print(cost {:.3f}s to init..format(e - s)) return obj return wraper@timerclass obj: def __init__(self): print(hello) sleep(3) print(obj)o = obj()
helloobjcost 3.005s to init.
类作为修饰器 上面两个例子都是以函数作为修饰器,因为函数才可以被调用(callable) decorator(wrap(func))。除了函数之外,我们也可以定义可被调用的类,只要添加 __call__方法即可:
class html(object): baking html tags! def __init__(self, tag=p): print(log: baking tag !.format(tag)) self.tag = tag def __call__(self, func): return lambda: {1}.format(self.tag, func(), self.tag) @html(html)@html(body)@html(div)def body(): return helloprint(body())
log: baking tag !log: baking tag !log: baking tag !hello
传递参数 在实际使用过程中,我们可能需要向修饰器传递参数,也有可能需要向被修饰的函数(或类)传递参数。按照语法约定,只要修饰器 @decorator中的 decorator是可调用即可, decorator(123)如果返回一个新的可调用函数,那么也是合理的,上面的 @html('html')即是一例,下面再以 flask 的路由修饰器为例说明如何传递参数给修饰器:
rules = {}def route(rule): def decorator(hand): rules.update({rule: hand}) return hand return decorator @route(/)def index(): print(hello world!)def home(): print(welcome home!)home = route(/home)(home)index()home()print(rules)
hello world!welcome home!{'/': , '/home': }
向被修饰的函数传递参数,要看我们的修饰器是如何作用的,如果像上面这个例子一样未执行被修饰函数只是将其原模原样地返回,则不需要任何处理(这就把函数当做普通的值一样看待即可):
@route(/login)def login(user = user, pwd = pwd): print(db.findone({{{}, {}}}).format(user, pwd))login(hail, python)
db.findone({hail, python})
如果需要在修饰器内执行,则需要稍微变动一下:
def log(f): def wraper(*args, **kargs): print(info: start logging) f(*args, **kargs) print(info: finish logging) return wraper@logdef run(hello = world): print(hello {}.format(hello))run(python)
info: start logginghello pythoninfo: finish logging
functools 由于修饰器将函数(或类)进行包装之后重新返回: func = decorator(func),那么有可能改变原本函数(或类)的一些信息,以上面的 html修饰器为例:
@html(body)def body(): return body content return hello, body!print(body.__name__)print(body.__doc__)
log: baking tag !none
因为 body = html(body)(body),而 html(body).__call__()返回的是一个 lambda函数,因此 body已经被替换成了 lambda,虽然都是可执行的函数,但原来定义的 body中的一些属性,例如 __doc__/ __name__/ __module__都被替换了(在本例中 __module__没变因为都在同一个文件中)。为了解决这一问题 python 提供了 functools标准库,其中包括了 update_wrapper和 wraps两个方法(源码)。其中 update_wrapper就是用来将原来函数的信息赋值给修饰器中返回的函数:
from functools import update_wrapperfunctools.update_wrapper(wrapper, wrapped[, assigned][, updated])class html(object): baking html tags! def __init__(self, tag=p): print(log: baking tag !.format(tag)) self.tag = tag def __call__(self, func): wraper = lambda: {1}.format(self.tag, func(), self.tag) update_wrapper(wraper, func) return wraper @html(body)def body(): return body content! return hello, body!print(body.__name__)print(body.__doc__)
log: baking tag !body return body content!
有趣的是 update_wrapper的用法本身就很像是修饰器,因此 functools.wraps就利用 functools.partial(还记得函数式编程中的偏应用吧!)将其变成一个修饰器:
from functools import update_wrapper, partialdef my_wraps(wrapped): return partial(update_wrapper, wrapped=wrapped)def log(func): @my_wraps(func) def wraper(): print(info: starting {}.format(func.__name__)) func() print(info: finishing {}.format(func.__name__)) return wraper@logdef run(): docs' of run print(running run...)print(run.__name__)print(run.__doc__)
run docs' of run
参考 python修饰器的函数式编程