4th Street Bar Hive-Bar

Hive-Bar Powered by Hive beta-fdb5b5b

Community post

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

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

140 upvotes $2.11

Replies (4)

Review before signing

Posting as . Signing with . Keychain permission: Posting. Hive Keychain will ask you to approve this action next.


  
Technical details

Operation fingerprint: