Python基礎-20裝飾器

来源:https://www.cnblogs.com/surpassme/archive/2020/06/08/12906122.html
-Advertisement-
Play Games

20.裝飾器 20.1 函數基礎知識 在Python中函數為一等公民,我們可以: 把函數賦值給變數 在函數中定義函數 在函數中返回函數 把函數傳遞給函數 20.1.1 把函數賦值給變數 在Python里,函數是對象,因此可以把它賦值給變數,如下所示: def hello(name="Surpass" ...


20.裝飾器

20.1 函數基礎知識

    在Python中函數為一等公民,我們可以:

  • 把函數賦值給變數
  • 在函數中定義函數
  • 在函數中返回函數
  • 把函數傳遞給函數

20.1.1 把函數賦值給變數

    在Python里,函數是對象,因此可以把它賦值給變數,如下所示:

def hello(name="Surpass"):
    return "Hello,"+name.capitalize()

    上述代碼定義了一個函數hello(),具體功能是把對輸入的姓名打招呼,並將姓名首字母轉換為大寫。下麵將函數賦值給變數,如下所示:

func=hello
print(func)

其輸出結果如下所示:

<function hello at 0x0000029D25213048>

    在上述代碼中,將hello賦值給func並輸出列印結果。從結果上來看,當不帶括弧使用hello時,僅輸出函數對象,而非調用函數,當帶上括弧時,則表示調用函數,如下所示:

func=hello
print(func())

其輸出結果如下所示:

Hello,Surpass

    既然函數是對象,那是不是可以嘗試刪除對象,來看看以下代碼:

def hello(name="Surpass"):
    return "Hello,"+name.capitalize()

func=hello
del hello
try:
    print(hello())
except Exception as ex:
    print(ex)

print(func())

其輸出結果如下所示:

name 'hello' is not defined
Hello,Surpass

    在上面代碼中,雖然hello函數已經刪除,但在刪除之前,已經賦值給變數func,所以不影響func的功能。因此可以得出以下總結:

函數是對象,可以將基賦值給其他變數variable,在調用時,需要添加括弧variable()

20.1.2 在函數中定義函數

    在Python中,可以在函數中定義函數,示例代碼如下所示:

def hello(name="Surpass"):
    def welcome(country="China"):
        return "Hello,"+name.capitalize()+",Welcome to "+country
    print(welcome())

hello()

其輸出結果如下所示:

Hello,Surpass,Welcome to China

    上述示例中,內部函數welcome表示歡迎來到某個國家,而且這個函數位於hello函數內部,只有通過調用hello函數時才能生效,測試代碼如下所示:

def hello(name="Surpass"):
    def welcome(country="China"):
        return "Hello,"+name.capitalize()+",Welcome to "+country
    print(welcome())

try:
    print(welcome())
except Exception as ex:
    print(ex)

其輸出結果如下所示:

name 'welcome' is not defined

    通過上面的示例代碼可以得到以下總結:

在函數funcA中可以定義函數funcB,但funcB無法在函數funcA之外進行調用

20.1.3 在函數中返回函數

    通過前面兩個示例,函數即可以返回其值,也可以返回其函數對象,示例代碼如下所示:

def hello(type=1):

    def name(name="Surpass"):
        return "My name is "+name

    def welcome(country="China"):
        return " Welcome to "+country

    def occupation(occupation="engineer"):
        return " I am "+occupation

    if type==1:
        return name
    elif type==2:
        return welcome
    else:
        return occupation

    在函數hello中定義了3個函數,然後根據type參數來返回不同的信息,在hello函數中,返回都為函數對象,可視為變數,運行以下代碼:

print(hello(1))
print(hello(1)())

func=hello(1)
print(func())

其輸出結果如下所示:

<function hello.<locals>.name at 0x000001D65783D5E8>
My name is Surpass
My name is Surpass

    註意上面在寫代碼上的區別,如果不加括弧,則代表僅返回函數對象,添加括弧則代表調用函數,總結如下所示:

在函數funcA中可以定義多個函數funcB...,並且可以把funcB當成對象進行返回

20.1.4 把函數傳遞給函數

    在Python中,既然一切都為對象,那函數也可以做參數傳遞給另一個函數,示例代碼如下所示:

import datetime
import time

def hello(name="Surpass"):
    print(f"Hello,{name}")

def testFunc(func):
    print(f"current time is {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    hello()
    time.sleep(2)
    print(f"current time is {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")

testFunc(hello)

其輸出結果如下所示:

current time is 2020-05-17 14:58:56
Hello,Surpass
current time is 2020-05-17 14:58:58

    在函數testFunc中接收參數為函數類型的函數hello,而且並未改變函數hello的任何內容,且實現在函數hello前後增加一些內容。因此我們可以總結如下所示:

函數funcA傳遞到函數funcB,函數funcB僅在函數funcA運行前後有操作,但不改變funcA,這就是裝飾器的錐形。

20.2 裝飾器

20.2.1 閉包

    維基的解釋如下所示:

在電腦科學中,閉包(Closure),又稱詞法閉包(Lexical Closure)或函數閉包(function closures),是引用了自由變數的函數。這個被引用的自由變數將和這個函數一同存在,即使已經離開了創造它的環境也不例外。所以,有另一種說法認為閉包是由函數和與其相關的引用環境組合而成的實體。閉包在運行時可以有多個實例,不同的引用環境和相同的函數組合可以產生不同的實例。

    Python裡面的閉包是一種高階函數,返回值為函數對象,簡單來講就是一個函數定義中引用了函數外定義的變數,並且該函數可以在其定義環境外執行,這種函數稱之為閉包。詳細如下圖所示:

01閉包定義.png

    在函數make_averager中,series為make_averager函數的局部變數,在averager函數中series稱之為自由變數(未在本地作用域中綁定的變數)

示例如下所示:

def outter(name):
    def inner():
        print(f"para is {name}")
    return inner

    內部函數inner()可以使用外部函數outter()的參數name,最後返回內部函數對象inner。可以按照在函數中返回函數進行調用。現在我們將outter換成decorator,inner換成wrapper,如下所示:

def decorator(name):
    def wrapper():
        print(f"para is {name}")
    return wrapper

    以上這種形式就是裝飾器,返回值為wrapper對象並等候調用,一旦被調用就運行 print(f"para is {name}")輸出結果。對於裝飾器而言,嚴格定義來講,參數是函數而不是變數,常用形式如下所示:

def decorator(func):
    def wrapper():
        return func()
    return wrapper

20.2.2 裝飾器初體驗

    我們先來看看一個簡單的示例,代碼如下所示:

def hello():
    print("call hello function")

def decorator(func):
    def wrapper():
        return func()
    return wrapper

tmp=decorator(hello)
tmp()

其輸出結果如下所示:

call hello function

    裝飾器的特性就是給原函數做裝飾,但不改變原函數的內容,在以下代碼中,希望在運行原函數func()之前,輸出原函數的名字:

def hello():
    print("call hello function")

def decorator(func):
    def wrapper():
        print(f"before call func name is {func.__name__}")
        return func()
    return wrapper

tmp=decorator(hello)
tmp()

其輸出結果如下所示:

before call func name is hello
call hello function

    經過前面的不斷學習,相信已經初步掌握了裝飾器的原理,如果每次都這樣調用是不是太麻煩了,於是Python提供了一種語法糖@裝飾函數寫在被裝飾函數上面即可。如下所示:

def decorator(func):
    def wrapper():
        print(f"before call func name is {func.__name__}")
        return func()
    return wrapper

@decorator
def hello():
    print("call hello function")

hello()

其輸出結果如下所示:

before call func name is hello
call hello function

    上面這種寫法等價於

tmp=decorator(hello)
tmp()

語法糖 (syntactic sugar):指電腦語言中添加的某種語法,對語言的功能沒有影響,但是讓程式員更方便地使用。

20.2.3 裝飾器知識點

20.2.3.1 多個裝飾器

    即裝飾器的特性是給函數進行裝飾,那是不是一個函數可以被多個函數進行裝飾,定義一個函數如下所示:

def hello(name="Surpass"):
    return f"Hello,{name}"

    針對以上這個函數,我們希望能完成以下功能:

  • 字元串全部大寫
  • 將返回的字元串拆分成單個單詞列表

    為完成以上功能,我們定義兩個裝飾器如下所示:

# 裝飾器一:
def toUpper(func):
    def wrapper():
        return func().upper()
    return wrapper

# 裝飾器二:
def splitStr(func):
    def wrapper():
        return func().split(",")
    return wrapper
@splitStr
@toUpper
def hello(name="Surpass"):
    return f"Hello,{name}"

print(hello())

其輸出結果如下所示:

['HELLO', 'SURPASS']

    以下代碼等價於:

print(splitStr(toUpper(hello))())

總結一下:一個函數存在多個裝飾器,順序是按照就近原則,即哪個函數靠近被裝飾函數,則優先進行裝飾,上面示例中@toUpper離被裝飾函數hello最近,優先運行,依次類推。

20.2.3.2 傳遞參數給裝飾函數

    裝飾函數就是wrapper(),因為要調用原函數func,一旦它有參數,則需要將這些參數傳遞給wrapper(),示例如下所示:

1.沒有參數的wrapper()

def decorator(func):
    def wrapper():
        funcName=func.__name__
        print(f"Befor call {funcName}")
        func()
        print(f"After call {funcName}")
    return wrapper

@decorator
def testFunc():
    print(f"call function is testFunc")

testFunc()

其輸出結果如下所示:

Befor call testFunc
call function is testFunc
After call testFunc

2.傳固定參數個數的wrapper()

    如果被裝飾函數有傳入參數,則在裝飾函數添加參數即可。

def decorator(func):
    def wrapper(args1,args2):
        funcName=func.__name__
        print(f"Befor call {funcName}")
        func(args1,args2)
        print(f"After call {funcName}")
    return wrapper

@decorator
def testFunc(name,age):
    print(f"Name is {name},age is {str(age)}")

testFunc("Surpass",28)

其輸出結果如下所示:

Befor call testFunc
Name is Surpass,age is 28
After call testFunc

3.帶返回值的wrapper()

    如果被裝飾函數有返回,則在裝飾函數中將被裝飾函數的結果賦給變數返回即可。

def decorator(func):
    def wrapper(args1,args2):
        funcName=func.__name__
        print(f"Befor call {funcName}")
        result=func(args1,args2)
        print(f"After call {funcName}")
        return result
    return wrapper

@decorator
def testFunc(name,age):
    return f"Name is {name},age is {str(age)}"

print(testFunc("Surpass",28))

其輸出結果如下所示:

Befor call testFunc
After call testFunc
Name is Surpass,age is 28

4.無固定參數個數的wrapper()
    在學習Python函數時,如果參數較多或無法確定參數個數,可以使用位置參數(*agrs)也可以使用關鍵字參數(**kwargs),示例代碼如下所示:

def decorator(func):
    def wrapper(*args,**kwargs):
        funcName=func.__name__
        print(f"Befor call {funcName}")
        result=func(*args,**kwargs)
        print(f"After call {funcName}")
        return result
    return wrapper

@decorator
def testFunc(*args,**kwargs):
    sum,dicSum=0,0
    for item in args:
        sum+=item
    for k,v in kwargs.items():
        dicSum+=v
    return sum,dicSum

print(testFunc(1,2,3,4,5,key1=1,key2=2,key3=5,key4=1000))

其輸出結果如下所示:

Befor call testFunc
After call testFunc
(15, 1008)
20.2.3.3 functools.wrap

    在裝飾器中,裝飾之後的函數名稱會變亂,如一個函數為hello(),其名稱為hello

def hello():
    pass
hello.__name__

其最終的函數名為:

'hello'

    而在裝飾器中,在使用@裝飾函數名稱之後,其名稱已經變成wrapper,原因也非常簡單,因為我們最終的調用形式都是decorator(被裝飾函數),而這個函數返回的是wrapper()函數,因此名稱為wrapper。示例代碼如下所示:

def decorator(func):
    def wrapper():
        return func()
    return wrapper

@decorator
def testFunc():
    pass

print(testFunc.__name__)

其輸出結果如下所示:

wrapper

    這種情況下,多種情況下應該不需要關註,但如果需要根據函數名來進行一些操作(如反射)則會出錯。如果仍然希望保持函數的原名,可以使用functools.wraps,示例代碼如下所示:

from functools import wraps

def decorator(func):
    @wraps(func)
    def wrapper():
        return func()
    return wrapper

@decorator
def testFunc():
    pass

print(testFunc.__name__)

其輸出結果如下所示:

testFunc

仔細看上面代碼,是不是裝飾函數又被裝飾了一次?

20.2.3.4 傳遞參數給裝飾器

    除了可以傳遞參數給裝飾函數(wapper),也可以傳遞參數給裝飾函數(decorator)。來看看以下示例,在示例中,只有裝飾函數有參數,裝飾器將數值保留2位小數,如下所示:

def digitalFormat(func):
    def wrapper(*args,**kwargs):
        result=func(*args,**kwargs)
        formatResult=round(result,2)
        return formatResult
    return wrapper


@digitalFormat
def add(a:float,b:float)->float:
    return a+b

print(add(12.09,19.12345))

其輸出結果如下所示:

31.21

    通過裝飾器,我們很快就達到要求。但有些情況,單純的數值可能並沒有太大意義,需要結合單位。假設上面示例返回為重量,則單位可能為g、kg等。那這種需求有沒有解決辦法了?示例代碼如下所示:

def unit(unit:str)->str:
    def digitalFormat(func):
        def wrapper(*args,**kwargs):
            result=func(*args,**kwargs)
            formatResult=f"{round(result,2)} {unit}"
            return formatResult
        return wrapper
    return digitalFormat


@unit("kg")
def add(a:float,b:float)->float:
    return a+b

print(add(12.09,19.12345))

其輸出結果如下所示:

31.21 kg

如果裝飾飾器本身需要傳遞參數,那麼再定義一層函數,將裝飾的參數傳入即可,是不是很簡單。

20.2.3.5 類裝飾器

1.使用類去裝飾函數

    前面實現的裝飾器都是針對函數而言,在實際應用中,類也可以作為裝飾器。在類裝飾器中主要依賴函數__call__(),每調用一個類的示例時,函數__call__()就會被執行一次,示例代碼如下所示:

class Count:

    def __init__(self,func):
        self.func=func
        self.callCount=0

    def __call__(self, *args, **kwargs):
        self.callCount+=1
        print(f"call count is {self.callCount}")
        return self.func(*args,**kwargs)

@Count
def testSample():
    print("Hello, Surpass")

for i in range(3):
    print(f"first call {testSample()}")

其輸出結果如下所示:

call count is 1
Hello, Surpass
first call None
call count is 2
Hello, Surpass
first call None
call count is 3
Hello, Surpass
first call None

2.使用函數去裝飾類

def decorator(num):
    def wrapper(cls):
        cls.callCount=num
        return cls
    return wrapper

@decorator(10)
class Count:
    callCount = 0
    def __init__(self):
       pass

    def __call__(self, *args, **kwargs):
        self.callCount+=1
        print(f"call count is {self.callCount}")
        return self.func(*args,**kwargs)


if __name__ == '__main__':
    count=Count()
    print(count.callCount)

其輸出結果如下所示:

10

20.4.4 何時使用裝飾器

    這個需要據實際的需求而定。比如需要測試每個函數運行時間,此時可以使用裝飾器,很輕鬆就能達到。另外裝飾器也可應用到身價認證、日誌記錄和輸入合理性檢查等等。

20.4.5 裝飾器實際案例

    在實際工作中,裝飾器經常會用來記錄日誌和時間,示例如下所示:

from functools import wraps
import logging
import time
def logType(logType):
    def myLogger(func):
        logging.basicConfig(filename=f"{func.__name__}.log",level=logging.INFO)
        @wraps(func)
        def wrapper(*args,**kwargs):
            logging.info(f" {logType} Run with args:{args} and kwargs is {kwargs}")
            return func(*args,**kwargs)
        return wrapper
    return myLogger

def myTimer(func):
    @wraps(func)
    def wrapper(*args,**kwargs):
        startTime=time.time()
        result=func(*args,**kwargs)
        endTime=time.time()
        print(f"{func.__name__} run time is {endTime-startTime} s ")
        return result
    return wrapper

@logType("Release - ")
@myTimer
def testWrapperA(name:str,color:str)->None:
    time.sleep(5)
    print(f"{testWrapperA.__name__} input paras is {(name,color)}")

@logType("Test - ")
@myTimer
def testWrapperB(name:str,color:str)->None:
    time.sleep(5)
    print(f"{testWrapperB.__name__} input paras is {(name,color)}")


if __name__ == '__main__':
    testWrapperA("apple","red")
    testWrapperB("apple", "red")

其輸出結果如下所示:

testWrapperA input paras is ('apple', 'red')
testWrapperA run time is 5.000441789627075 s
testWrapperB input paras is ('apple', 'red')
testWrapperB run time is 5.000349521636963 s

日誌記錄信息如下所示:

02日誌記錄信息.png

20.4.6 小結

    裝飾器就是接受參數類型為函數或類並返回函數或類的函數,通過裝飾器函數,在不改變原函數的基礎上添加新的功能。示意圖如下所示:

03裝飾器示意圖.png

本文地址:https://www.cnblogs.com/surpassme/p/12906122.html

本文同步在微信訂閱號上發佈,如各位小伙伴們喜歡我的文章,也可以關註我的微信訂閱號:woaitest,或掃描下麵的二維碼添加關註:
MyQRCode.jpg


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 安裝mysql yum repository wget -i -c http://dev.mysql.com/get/mysql57-community-release-el7-10.noarch.rpm yum -y install mysql57-community-release-el7-10 ...
  • 近期新接觸sqlserver、oracle資料庫,發現指定返回記錄總數居然都和mysql不同: Mysql:select XXX where XXX limit N Sqlserver: select TOP N XXX Oracle:select XXXX where rownum < (N+1) ...
  • 常用操作 1.查看創建表參數 提取完整的DDL: SELECT DBMS_METADATA.GET_DDL('TABLE','table_name') FROM DUAL; 2.指定返回記錄數 select XXX from XXX where rownum<n 3.查詢指定列的所有值且每個值只顯示 ...
  • 這是一次本地壓力測試,由於預設Oracle 10g的資料庫最大連接數是150。但是要程式的壓力測試要用到300。 於是我參考網上資料,執行下麵兩行命令,修改最大連接數後,重啟oracle伺服器,就發生了錯誤提示oracle無法登陸。 step 1: 修改最大連接數 # 查詢 當前最大連接數selec ...
  • 1.背景環境 本文章來自最近做的項目模塊的思考和總結,主要講思路不涉及過多的基礎和實現細節。 需求:統計出來納稅人名稱、行業、近一年業務量(辦稅服務廳、電子稅務局、自助渠道),近一年業務量top5(辦稅服務廳、電子稅務局、自助渠道)、近一年納稅金額、近一年申報數、近一年用票數。支持根據所屬稅務機關分 ...
  • 列表標簽 無序列表: 無序列表是一個項目的列表,此列項目使用粗體圓點(典型的小黑圓圈)進行標記。 無序列表使用 <ul> 標簽 <ul> <li>劉備</li> <li>關羽</li> <li>孫尚香</li> <li>諸葛亮</li> <li>劉禪</li> </ul> 有序列表: 有序列表也是一 ...
  • # 從零開始的前端生活-理解content(二) 應用 清除浮動 偽元素加content最常見的應用是清除浮動帶來的影響 .clear::after{ content:''; display:table; clear:both; } 字元內容的生成 content還可以插入Unicode字元(萬國 ...
  • 關於《SpringBoot-2.3容器化技術》系列 《SpringBoot-2.3容器化技術》系列,旨在和大家一起學習實踐2.3版本帶來的最新容器化技術,讓咱們的Java應用更加適應容器化環境,在雲計算時代依舊緊跟主流,保持競爭力; 全系列文章分為主題和輔助兩部分,主題部分如下: 《體驗Spring ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...