多個裝飾器修飾一個函數時的調用順序


參考教程: https://blog.csdn.net/jyhhhhhhh/article/details/54627850

#當有多個裝飾器裝飾一個函數時,他們的執行順序

#觀察下方的代碼就會發現
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):
    #decorator_b(decorator_a(f))
    #而以上代碼【decorator_b(decorator_a(f))】返回的是inner_b,所以執行的時候是先執行inner_b
    #然后在執行【decorator_a(f)】返回的inner_a  .最終在調用f(1)的時候,函數inner_b輸出'Get in inner_b'
    #然后執行inner_a輸出Get in decorator_a,最后執行func(),即f
    
    
    #調用時,函數的順序
    '''
    @decorator_b
    @decorator_a
    def f(x)
    
    相當於-------decorator_b(decorator_a(f)),其中每一層返回的都是一個函數對象,沒有調用
    之后返回時的函數對象--------inner_b(inner_a)
    然后最后一行當我們對 f 傳入參數1進行調用時, inner_b 被調用了,它會先打印 Get in inner_b ,
    然后在 inner_b 內部調用了 inner_a 所以會再打印 Get in inner_a, 然后再 inner_a 內部調用的原來的 f, 
    並且將結果作為最終的返回
    '''
    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


實際中的使用
在實際應用的場景中,當我們采用上面的方式寫了兩個裝飾方法,比如先驗證有沒有登錄@login_required,
再驗證權限夠不夠時@permision_allowed時,我們采用下面的順序來裝飾函數:

@login_required
@permision_allowed
def f()
  # Do something

  




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM