# 探究多个装饰器执行顺序

2,754次阅读

## 疑问

def decorator_a(func):
print 'Get in decorator_a'
def inner_a(*args, **kwargs):
print 'Get in inner_a'
return func(*args, **kwargs)
return inner_a

def decorator_b(func):
print 'Get in decorator_b'
def inner_b(*args, **kwargs):
print 'Get in inner_b'
return func(*args, **kwargs)
return inner_b

@decorator_b
@decorator_a
def f(x):
print 'Get in f'
return x * 2

f(1)


Get in decorator_a
Get in decorator_b
Get in inner_b
Get in inner_a
Get in f


## 装饰器函数在被装饰函数定义好后立即执行

def decorator_a(func):
print 'Get in decorator_a'
def inner_a(*args, **kwargs):
print 'Get in inner_a'
return func(*args, **kwargs)
return inner_a

@decorator_a
def f(x):
print 'Get in f'
return x * 2


@decorator_a
def f(x):
print 'Get in f'
return x * 2

# 相当于
def f(x):
print 'Get in f'
return x * 2

f = decorator_a(f)


## 疑问的解释

@decorator_b
@decorator_a
def f(x):
print 'Get in f'
return x * 2


➜  test git:(master) ✗ python
Python 2.7.11 (default, Jan 22 2016, 08:29:18)
[GCC 4.2.1 Compatible Apple LLVM 7.0.2 (clang-700.1.81)] on darwin
>>> import test13
Get in decorator_a
Get in decorator_b
>>> test13.f(1)
Get in inner_b
Get in inner_a
Get in f
2
>>> test13.f(2)
Get in inner_b
Get in inner_a
Get in f
4
>>>


@login_required
@permision_allowed
def f()
# Do something
return