欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

詳解Python函數(shù)式編程之裝飾器

 更新時間:2022年03月03日 16:30:00   作者:愛吃糖的范同學  
這篇文章主要為大家詳細介紹了Python函數(shù)式編程之裝飾器,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助

一、裝飾器的本質(zhì):

裝飾器(decorator)本質(zhì)是函數(shù)閉包(function closure)的語法糖(Syntactic sugar)

函數(shù)閉包(function closure):

函數(shù)閉包是函數(shù)式語言(函數(shù)是一等公民,可作為變量使用)中的術語。函數(shù)閉包:一個函數(shù),其參數(shù)和返回值都是函數(shù),用于增強函數(shù)功能,面向切面編程(AOP)

import time
# 控制臺打印100以內(nèi)的奇數(shù):
def print_odd():
    for i in range(100):
        if i % 2 == 1:
            print(i)
# 函數(shù)閉包:用于增強函數(shù)func:給函數(shù)func增加統(tǒng)計時間的功能:
def count_time_wrapper(func):
    def improved_func():
        start_time = time.time()
        func()
        end_time = time.time()
        print(f"It takes {end_time - start_time} S to find all the odds in range !!!")
    return improved_func
if __name__ == '__main__':
    # 調(diào)用count_time_wrapper增強函數(shù)
    print_odd = count_time_wrapper(print_odd)
    print_odd()

閉包本質(zhì)上是一個函數(shù),閉包函數(shù)的傳入?yún)?shù)和返回值都是函數(shù),閉包函數(shù)得到返回值函數(shù)是對傳入函數(shù)增強后的結(jié)果。

日志裝飾器:

def log_wrapper(func):
    """
    閉包,用于增強函數(shù)func: 給func增加日志功能
    """
    def improved_func():
        start_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))  # 起始時間
        func()  # 執(zhí)行函數(shù)
        end_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))  # 結(jié)束時間
        print("Logging: func:{} runs from {} to {}".format(func.__name__, start_time, end_time))
    return improved_func

二、裝飾器使用方法:

通過裝飾器進行函數(shù)增強,只是一種語法糖,本質(zhì)上跟上個程序(使用函數(shù)閉包)完全一致。

import time
# 函數(shù)閉包:用于增強函數(shù)func:給函數(shù)func增加統(tǒng)計時間的功能:
def count_time_wrapper(func):
    def improved_func():
        start_time = time.time()
        func()
        end_time = time.time()
        print(f"It takes {end_time - start_time} S to find all the odds in range !!!")
    return improved_func
# 控制臺打印100以內(nèi)的奇數(shù):
@count_time_wrapper  # 添加裝飾器
def print_odd():
    for i in range(100):
        if i % 2 == 1:
            print(i)
if __name__ == '__main__':
    # 使用  @裝飾器(增強函數(shù)名) 給當前函數(shù)添加裝飾器,等價于執(zhí)行了下面這條語句:
    # print_odd = count_time_wrapper(print_odd)
    print_odd()

裝飾器在第一次調(diào)用被裝飾函數(shù)時進行增強,只增強一次,下次調(diào)用仍然是調(diào)用增強后的函數(shù),不會重復執(zhí)行增強!

保留函數(shù)參數(shù)和返回值的函數(shù)閉包:

  • 之前所寫的函數(shù)閉包,在增強主要功能函數(shù)時,沒有保留原主要功能函數(shù)的參數(shù)列表和返回值。
  • 一個保留參數(shù)列表和返回值的函數(shù)閉包寫法:
def general_wrapper(func):
    def improved_func(*args, **kwargs):
        # 增強函數(shù)功能:
        ret = func(*args, **kwargs)
        # 增強函數(shù)功能:
        return ret
    return improved_func

優(yōu)化裝飾器(參數(shù)傳遞、設置返回值): 

import time
# 函數(shù)閉包:用于增強函數(shù)func:給函數(shù)func增加統(tǒng)計時間的功能:
def count_time_wrapper(func):
    # 增強函數(shù):
    def improved_func(*args, **kwargs):
        start_time = time.time()
        result = func(*args, **kwargs)
        end_time = time.time()
        print(f"It takes {end_time - start_time} S to find all the odds in range !!!")
        # 原函數(shù)返回值
        return result
    return improved_func
# 計算0-lim奇數(shù)之和:
@count_time_wrapper
def count_odds(lim):
    cnt = 0
    for i in range(lim):
        if i % 2 == 1:
            cnt = cnt + i
    return cnt
if __name__ == '__main__':
    result = count_odds(10000000)
    print(f"計算結(jié)果為{result}!")

三、多個裝飾器的執(zhí)行順序:

# 裝飾器1:
def wrapper1(func1):
    print("set func1")  # 在wrapper1裝飾函數(shù)時輸出
    def improved_func1(*args, **kwargs):
        print("call func1")  # 在wrapper1裝飾過的函數(shù)被調(diào)用時輸出
        func1(*args, **kwargs)
        return None
    return improved_func1
# 裝飾器2:
def wrapper2(func2):
    print("set func2")  # 在wrapper2裝飾函數(shù)時輸出
    def improved_func2(*args, **kwargs):
        print("call func1")  # 在wrapper2裝飾過的函數(shù)被調(diào)用時輸出
        func2(*args, **kwargs)
        return None
    return improved_func2
@wrapper1
@wrapper2
def original_func():
    pass
if __name__ == '__main__':
    original_func()
    print("------------")
    original_func()

這里得到的執(zhí)行結(jié)果是,wrapper2裝飾器先執(zhí)行,原因是因為:程序從上往下執(zhí)行,當運行到:

@wrapper1
@wrapper2
def original_func():
    pass

這段代碼時,使用函數(shù)閉包的方式解析為:

original_func = wrapper1(wrapper2(original_func))

所以先進行wrapper2裝飾,然后再對被wrapper2裝飾完成的增強函數(shù)再由wrapper1進行裝飾,返回最終的增強函數(shù)。

四、創(chuàng)建帶參數(shù)的裝飾器:

裝飾器允許傳入?yún)?shù),一個攜帶了參數(shù)的裝飾器將有三層函數(shù),如下所示:

import functools
def log_with_param(text):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            print('call %s():' % func.__name__)
            print('args = {}'.format(*args))
            print('log_param = {}'.format(text))
            return func(*args, **kwargs)
        return wrapper
    return decorator
@log_with_param("param!!!")
def test_with_param(p):
    print(test_with_param.__name__)
if __name__ == '__main__':
    test_with_param("test")

將其 @語法 去除,恢復函數(shù)調(diào)用的形式:

# 傳入裝飾器的參數(shù),并接收返回的decorator函數(shù)
decorator = log_with_param("param!!!")
# 傳入test_with_param函數(shù)
wrapper = decorator(test_with_param)
# 調(diào)用裝飾器函數(shù)
wrapper("I'm a param")

總結(jié)

本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關注腳本之家的更多內(nèi)容! 

相關文章

  • educoder之Python數(shù)值計算庫Numpy圖像處理詳解

    educoder之Python數(shù)值計算庫Numpy圖像處理詳解

    這篇文章主要為大家介紹了educoder之Python數(shù)值計算庫Numpy圖像處理詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-04-04
  • pycharm設置注釋顏色的方法

    pycharm設置注釋顏色的方法

    今天小編就為大家分享一篇pycharm設置注釋顏色的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-05-05
  • python+opencv+caffe+攝像頭做目標檢測的實例代碼

    python+opencv+caffe+攝像頭做目標檢測的實例代碼

    今天小編就為大家分享一篇python+opencv+caffe+攝像頭做目標檢測的實例代碼,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-08-08
  • 在Python中用GDAL實現(xiàn)矢量對柵格的切割實例

    在Python中用GDAL實現(xiàn)矢量對柵格的切割實例

    這篇文章主要介紹了在Python中用GDAL實現(xiàn)矢量對柵格的切割實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-03-03
  • Python與C語言分別完成排序流程

    Python與C語言分別完成排序流程

    這篇文章主要介紹了Python與C語言分別完成排序的實例,在Python與C語言基本類型的排序中特別有用,下面我們一起進入文章學習更詳細的內(nèi)容吧,需要的朋友可以參考下
    2022-03-03
  • Pytorch環(huán)境搭建與基本語法

    Pytorch環(huán)境搭建與基本語法

    這篇文章主要介紹了Pytorch環(huán)境搭建與基本語法,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-06-06
  • Python圖像灰度變換及圖像數(shù)組操作

    Python圖像灰度變換及圖像數(shù)組操作

    這篇文章主要介紹了Python圖像灰度變換及圖像數(shù)組操作的相關資料,需要的朋友可以參考下
    2016-01-01
  • python進程結(jié)束后端口占用問題解析

    python進程結(jié)束后端口占用問題解析

    這篇文章主要為大家介紹了python中在進程結(jié)束后端口依然被占用的問題解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步
    2022-01-01
  • python中xrange和range的區(qū)別

    python中xrange和range的區(qū)別

    這篇文章主要介紹了python中xrange和range的區(qū)別,需要的朋友可以參考下
    2014-05-05
  • python中使用 xlwt 操作excel的常見方法與問題

    python中使用 xlwt 操作excel的常見方法與問題

    這篇文章主要給大家介紹了關于python中使用 xlwt 操作excel的常見方法與問題的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2019-01-01

最新評論