iT邦幫忙

2022 iThome 鐵人賽

DAY 12
0
Modern Web

flask系列 第 12

Day12 Python 進階3

  • 分享至 

  • xImage
  •  

裝飾器

裝飾器 decorator 是 Python 的一種程式設計模式,裝飾器本質上是一個 Python 函式或類 ( class ),它可以讓其他函式或類,在不需要做任何代碼修改的前提下增加額外功能,裝飾器的返回值也是一個函式或類對象, 有了裝飾器,就可以抽離與函式功能本身無關的程式碼,放到裝飾器中並繼續重複使用。

定義一個裝飾器函式 a 和一個被裝飾的函式 b,當 b 函式執行後,會看見 a 運算後的結果,套用在 b 函式上

def a(func):
    print('hello')
    return func

def b():
    print('world')

a(b)()
hello
world

語法糖

計算機語言中特殊的某種語法這種語法對語言的功能並沒有影響對於程式設計師有更好的易用性能夠增加程式的可讀性
在 Python 中,使用「@」當做裝飾器使用的語法糖符號

使用語法糖「@」包裝,能達到簡化的效果。

def a(func):
    print('hello')
    return func
@a
def b():
    print('world')

b()
hello
world

多個裝飾器

如果有多個裝飾器,執行的順序將會「由下而上」觸發

定義兩個裝飾器函式 a 、 c 和一個被裝飾的函式 b,當 b 函式執行後,會先看見 a 運算後的結果,再看見 c 運算後的結果,最後套用在 b 函式上

def a(func):
    print('hello')
    return func


def c(func):
    print('=======')
    return func


@c
@a
def b():
    print('world')


b()

hello
=======
world

參數處理

如果裝飾器遇到帶有參數的函式,同樣能將參數一併帶入處理

def a(func):
    def c(name):
        print('hello')
        func(name)
    return c


@a
def b(name):
    print(name)


b('alan')
hello
alan

上一篇
Day11 Python 進階2
下一篇
Day13 flask 介紹
系列文
flask30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
arguskao
iT邦新手 4 級 ‧ 2023-01-11 15:37:31

這一段完全看不懂呀

我要留言

立即登入留言