Python的修饰器的英文名叫Decorator,主要作用是对一个已有的模块做一些“修饰工作”,所谓修饰工作就是想给现有的模块加上一些小装饰(一些小功能,这些小功能可能好多模块都会用到),但又不让这个小装饰(小功能)侵入到原有的模块中的代码里去。
#! /usr/bin/env python
# -*- coding: utf-8 -*-
def decorator_1(func):
print 'decorator_1 called'
def wrapper(*arg):
print 'before %s' % func.__name__
func(*arg)
print 'after %s' % func.__name__
return wrapper
def decorator_2(arg):
print 'decorator_2 called, with ', arg
def _decorator(func):
print '_decorator_2 called'
def wrapper(*arg):
print 'before %s' % func.__name__
func(*arg)
print 'after %s' % func.__name__
return wrapper
return _decorator
def decorator_3(arg):
print 'decorator_3 called, with ', arg
def _decorator(func):
print '_decorator_3 called'
def wrapper(*arg):
print 'before %s' % func.__name__
func(*arg)
print 'after %s' % func.__name__
return wrapper
return _decorator
@decorator_3('d3')
@decorator_2('d2')
@decorator_1
def func(*arg):
print 'func called with ', arg
if __name__ == "__main__":
#等价于 decorator_3('d3')(decorator_2('d2')(decorator_1(func)))('arg1', 'arg2')
func('arg1', 'arg2')
输出:
decorator_3 called, with d3
decorator_2 called, with d2
decorator_1 called
_decorator_2 called
_decorator_3 called
before wrapper
before wrapper
before func
func called with ('arg1', 'arg2')
after func
after wrapper
after wrapper
注意输出顺序