Python装饰器调用顺序

in #programming6 years ago (edited)

写了不少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

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

Sort:  

Hello! Your post has been resteemed and upvoted by @ilovecoding because we love coding! Keep up good work! Consider upvoting this comment to support the @ilovecoding and increase your future rewards! ^_^ Steem On!

Reply !stop to disable the comment. Thanks!

你今天过的开心吗?来 @steemgg 玩游戏吧,决战到天亮如果不想再收到我的留言,请回复“取消”。

不明觉厉

Congratulations @skenan! You have completed the following achievement on the Steem blockchain and have been rewarded with new badge(s) :

Award for the number of upvotes received

Click on the badge to view your Board of Honor.
If you no longer want to receive notifications, reply to this comment with the word STOP

Do not miss the last post from @steemitboard:

SteemitBoard Ranking update - Steem Power, Followers and Following added

Support SteemitBoard's project! Vote for its witness and get one more award!

Coin Marketplace

STEEM 0.21
TRX 0.20
JST 0.034
BTC 90827.60
ETH 3116.50
USDT 1.00
SBD 2.97