1. 程式人生 > 其它 >python裝飾器(二)裝飾器的使用

python裝飾器(二)裝飾器的使用

裝飾器的作用:

*裝飾器其實就是利用閉包功能對函式進行增強
*裝飾器格式為: @閉包函式名

簡單案例:
def show(fun1):
    def show_in():
        fun1()
        sumdate = 0
        for i in range(1,101):
            if i%2 == 1 :
                sumdate += i
        print(sumdate)
    return show_in

@show
def odd_sum():
    print('1到100的奇數和:')

odd_sum()

輸出結果:
1到100的奇數和:
2500

  • 拿閉包的程式碼進行比較,輸出結果是一樣的
def show(fun1):
    def show_in():
        fun1()
        sumdate = 0
        for i in range(1,101):
            if i%2 == 1 :
                sumdate += i
        print(sumdate)
    return show_in

def odd_sum():
    print('1到100的奇數和:')

odd_sum = show(odd_sum)
odd_sum()
  • 案例分析有裝飾器的程式碼,並沒有像閉包那樣,明顯的有odd_sum = show(odd_sum)語句,只是把這句省略了,利用裝飾窮程式中會自動呼叫odd_sum = show(odd_sum)語句

  • 在主函式上方加上@show(@後面接輔助函式名),就表明將主函式作為引數傳入show函式fun1中,讓show函式和odd_sum函式具有了聯絡

  • 看看下面這個案例

def show(fun1):
    print('1到100的奇數和:')
    def show_in():
        fun1()
        sumdate = 0
        for i in range(1,101):
            if i%2 == 1 :
                sumdate += i
        print(sumdate)
    return show_in

@show
def odd_sum():
    pass

odd_sum()
print('-------------')
odd_sum()

輸出結果:
1到100的奇數和:
2500
'-------------'
2500

*案例分析第一次顯示了“1到100的奇數和:”,第二次卻沒有
*第二次只會使用這個已經增強的函式,不會顯示過程
*僅僅只會使用這一段

def show_in():
        fun1()
        sumdate = 0
        for i in range(1,101):
            if i%2 == 1 :
                sumdate += i
        print(sumdate)