skenan avatar

Python装饰器调用顺序

skenan

Published: 17 Oct 2018 › Updated: 17 Oct 2018Python装饰器调用顺序

Python装饰器调用顺序

写了不少python code,但有时还是容易记混装饰器的执行顺序,趁着刚复习完,简单记录一下...

例子

def one(func):
    print('----one----')
    def inside_one():
        print('----inside-one----')
        func()
    return inside_one

def two(func):
    print('----two----')
    def inside_two():
        print('----inside-two----')
        func()
    return inside_two

@one
@two
def demo():
    print('----3----')

demo()

执行顺序

----two----
----one----
----inside-one----
----inside-two----
----3----

这是因为在demo函数未调用前,要先生成一个新的demo函数为one(two(demo))

生成新函数的时的顺序是从下向上

----two----
----one----

当调用 demo()时,执行生成后的函数

----inside-one----
----inside-two----
----3----

应用

@app.route('/')
@login_required
@check_permission
def test():
     pass

这样保证先登录,后验证权限

Leave Python装饰器调用顺序 to:

Written by

生活本应该被记录

Read more #programming posts


Best Posts From skenan

We have not curated any of skenan's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.

More Posts From skenan