# Python装饰器顺序探究

Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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

### 1.1 疑问

```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

```

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

```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)

```

### 1.4 疑问的解释

```@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

```