搜尋
首頁後端開發Python教學Python 裝飾器:綜合指南

Python Decorators: A Comprehensive Guide

開始使用Python程式設計時,如果沒記錯的話,版本是3.3。因此,當我開始編程時,Python 社群很早就可以使用裝飾器了。

Python 2.2 版本引入了函數裝飾器,Python 2.6 版本引入了類別裝飾器。

就我個人而言,我認為 Python 的裝飾器功能是該語言的一個非常強大的功能。

實際上,我的目標是製作一系列有關 Python 中最難理解的主題的文章。我打算一一涵蓋這些主題,大概有十多個。

在本文中,我將嘗試盡可能多地觸及裝飾器主題的每個部分。

1. 歷史背景

  • 早期(Python 2.2 之前): 在裝飾器之前,修改函數或類別通常需要手動包裝或猴子修補,這很麻煩且可讀性較差。
  • 元類別 (Python 2.2): 元類別提供了一種控制類別創建的方法,提供了裝飾器稍後提供的一些功能,但對於簡單的修改來說它們很複雜。
  • PEP 318 (Python 2.4): 裝飾器透過 PEP 318 在 Python 2.4 中正式引入。該提案受到 Java 中註釋的啟發,旨在提供一種更清晰、更具聲明性的方式來修改函數和方法.
  • 類別裝飾器 (Python 2.6): Python 2.6 擴展了對類別的裝飾器支持,進一步增強了類別的多功能性。
  • 廣泛採用: 裝飾器很快就成為一種流行的功能,廣泛用於 Flask 和 Django 等框架中,用於路由、驗證等。

2.什麼是裝飾器?

本質上,裝飾器是Python中的一種設計模式,它允許您修改函數或類別的行為而不改變其核心結構。裝飾器是元程式設計的一種形式,您本質上是在編寫操作其他程式碼的程式碼。

您知道 Python 使用以下順序給出的範圍來解析名稱:

  1. 本地
  2. 附上
  3. 全球
  4. 內建

裝飾器是坐封閉作用域,這與閉包概念密切相關。

關鍵思想:裝飾器將函數作為輸入,向其添加一些功能,然後返回修改後的函數。

類比:將裝飾器視為禮品包裝紙。您有一件禮物(原始功能),然後用裝飾紙(裝飾器)將其包裹起來,使其看起來更漂亮或添加額外的功能(例如蝴蝶結或卡片)。裡面的禮物保持不變,但它的呈現或相關動作得到了增強。

A) 裝飾器變體:基於函數與基於類

Python 中的大多數裝飾器都是使用函數實現的,但您也可以使用類別建立裝飾器。
基於函數的裝飾器更常見、更簡單,而基於類別的裝飾器提供了額外的靈活性。

基於函數的基本裝飾器語法

def my_decorator(func):
    def wrapper(*args, **kwargs):
        # Do something before calling the decorated function
        print("Before function call")
        result = func(*args, **kwargs)
        # Do something after calling the decorated function
        print("After function call")
        return result
    return wrapper

@my_decorator
def say_hello(name):
    print(f"Hello, {name}!")

say_hello("World")

說明:

  • my_decorator 是裝飾器函數。它需要將函數 func 修飾為輸入。
  • 包裝器是包裝原始函數呼叫的內部函數。它可以在原始函數之前和之後執行程式碼。
  • @my_decorator 是裝飾器語法。相當於 say_hello = my_decorator(say_hello).

基於類別的基本裝飾器語法

它們使用類別而不是函數來定義裝飾器。

class MyDecorator:
    def __init__(self, func):
        self.func = func

    def __call__(self, *args, **kwargs):
        # Do something before calling the decorated function
        print("Before function call")
        result = self.func(*args, **kwargs)
        # Do something after calling the decorated function
        print("After function call")
        return result

@MyDecorator
def say_hello(name):
    print(f"Hello, {name}!")

say_hello("World")

說明:

  • MyDecorator 是一個充當裝飾器的類別。
  • __init__方法儲存要裝飾的函數。
  • __call__ 方法使類別實例可調用,允許它像函數一樣使用。

B) 實作一個簡單的裝飾器

裝飾器的基本概念是它們是將另一個函數作為參數並擴展其行為而不明確修改它的函數。
這是最簡單的形式:

def my_decorator(func):
    def wrapper():
        print("Something is happening before the function is called.")
        func()
        print("Something is happening after the function is called.")
    return wrapper

# Using the decorator with @ syntax
@my_decorator
def say_hello():
    print("Hello!")

# When we call say_hello()
say_hello()

# This is equivalent to:
# say_hello = my_decorator(say_hello)

C) 實作有參數的裝飾器

讓我們建立一個記錄函數執行時間的裝飾器:

def decorator_with_args(func):
    def wrapper(*args, **kwargs):    # Accept any number of arguments
        print(f"Arguments received: {args}, {kwargs}")
        return func(*args, **kwargs)  # Pass arguments to the original function
    return wrapper

@decorator_with_args
def greet(name, greeting="Hello"):
    print(f"{greeting}, {name}!")

greet("Alice", greeting="Hi")  # Prints arguments then "Hi, Alice!"

D) 實現參數化裝飾器

這些裝飾器可以接受自己的參數:

def repeat(times):
    def decorator(func):
        def wrapper(*args, **kwargs):
            for _ in range(times):
                result = func(*args, **kwargs)
            return result
        return wrapper
    return decorator

@repeat(times=3)
def greet(name):
    print(f"Hello {name}")
    return "Done"

greet("Bob")  # Prints "Hello Bob" three times

E) 實作類別裝飾器

def singleton(cls):
    instances = {}
    def get_instance(*args, **kwargs):
        if cls not in instances:
            instances[cls] = cls(*args, **kwargs)
        return instances[cls]
    return get_instance

@singleton
class DatabaseConnection:
    def __init__(self):
        print("Initializing database connection")

# Creating multiple instances actually returns the same instance
db1 = DatabaseConnection()  # Prints initialization
db2 = DatabaseConnection()  # No initialization printed
print(db1 is db2)  # True

F) 實作方法裝飾器

這些是專門為類別方法設計的:

def debug_method(func):
    def wrapper(self, *args, **kwargs):
        print(f"Calling method {func.__name__} of {self.__class__.__name__}")
        return func(self, *args, **kwargs)
    return wrapper

class MyClass:
    @debug_method
    def my_method(self, x, y):
        return x + y

obj = MyClass()
print(obj.my_method(5, 3))

G) 實現裝飾器鏈接

多個裝飾器可以應用於單一函數:

def bold(func):
    def wrapper():
        return "<b>" + func() + "</b>"
    return wrapper

def italic(func):
    def wrapper():
        return "<i>" + func() + "</i>"
    return wrapper

@bold
@italic
def greet():
    return "Hello!"

print(greet())  # Outputs: <b><i>Hello!</i></b>

說明:

  • 裝飾器是從下到上應用的。
  • 這更像是我們在數學中所做的:f(g(x))。
  • 先塗抹斜體,然後再應用粗體。

H)如果我們不使用 @functools.wraps 會發生什麼事?

functools.wraps 裝飾器(請參閱文件)是一個輔助函數,當您使用裝飾器包裝原始函數時,它會保留原始函數的元資料(如其名稱、文件字串和簽名)。如果您不使用它,您將丟失這些重要資訊。

範例:

def my_decorator(func):
    def wrapper(*args, **kwargs):
        """Wrapper docstring"""
        return func(*args, **kwargs)
    return wrapper

@my_decorator
def my_function():
    """My function docstring"""
    pass

print(my_function.__name__)
print(my_function.__doc__)

輸出:

wrapper
Wrapper docstring

問題:

  • 原始函數的名稱(my_function)和文件字串(「我的函數文件字串」)遺失。
  • 這會使調試和自省變得困難。

解:使用 functools.wraps):

def my_decorator(func):
    def wrapper(*args, **kwargs):
        # Do something before calling the decorated function
        print("Before function call")
        result = func(*args, **kwargs)
        # Do something after calling the decorated function
        print("After function call")
        return result
    return wrapper

@my_decorator
def say_hello(name):
    print(f"Hello, {name}!")

say_hello("World")

輸出:

class MyDecorator:
    def __init__(self, func):
        self.func = func

    def __call__(self, *args, **kwargs):
        # Do something before calling the decorated function
        print("Before function call")
        result = self.func(*args, **kwargs)
        # Do something after calling the decorated function
        print("After function call")
        return result

@MyDecorator
def say_hello(name):
    print(f"Hello, {name}!")

say_hello("World")

functools.wraps 的好處:

  • 保留函數元資料。
  • 提高程式碼可讀性和可維護性。
  • 讓除錯更容易。
  • 幫助使用內省工具和文件產生器。

I) 具有狀態的裝飾器

裝飾器也可以維護函數呼叫之間的狀態。這對於緩存或計算函數呼叫等場景特別有用。

def my_decorator(func):
    def wrapper():
        print("Something is happening before the function is called.")
        func()
        print("Something is happening after the function is called.")
    return wrapper

# Using the decorator with @ syntax
@my_decorator
def say_hello():
    print("Hello!")

# When we call say_hello()
say_hello()

# This is equivalent to:
# say_hello = my_decorator(say_hello)

輸出:

def decorator_with_args(func):
    def wrapper(*args, **kwargs):    # Accept any number of arguments
        print(f"Arguments received: {args}, {kwargs}")
        return func(*args, **kwargs)  # Pass arguments to the original function
    return wrapper

@decorator_with_args
def greet(name, greeting="Hello"):
    print(f"{greeting}, {name}!")

greet("Alice", greeting="Hi")  # Prints arguments then "Hi, Alice!"

說明:

包裝函數維護一個計數器(呼叫),每次呼叫裝飾函數時該計數器都會增加。
這是一個如何使用裝飾器來維護狀態的簡單範例。

J) Python 裝飾器的最佳實踐

  • 使用 functools.wraps: 始終在裝飾器中使用 @functools.wraps 保留原始函數的元資料。
  • 保持裝飾器簡單: 理想情況下,裝飾器應該做一件特定的事情並且做得很好。這使得它們更可重複使用且更易於理解。
  • 記錄你的裝飾器:解釋你的裝飾器做了什麼,它需要什麼參數,以及它回傳什麼。
  • 測試你的裝飾器:編寫單元測試以確保你的裝飾器在各種場景下按預期工作。
  • 考慮連結順序:連結多個裝飾器時請注意順序,因為它會影響執行流程。

K) 糟糕的實現(反模式)

  • 過於複雜的裝飾器: 避免創建過於複雜或嘗試做太多事情的裝飾器。這使得它們難以理解、維護和調試。
  • 忽略 functools.wraps: 忘記使用 @functools.wraps 會導致函數元資料遺失,進而導致自省和偵錯問題。
  • 副作用: 理想情況下,裝飾器除了修改裝飾函數之外不應產生意外的副作用。
  • 硬編碼值: 避免在裝飾器中對值進行硬編碼。相反,使用裝飾器工廠來使其可配置。
  • 未正確處理參數: 如果裝飾器要與各種函數一起使用,請確保您的包裝函數可以使用 *args 和 **kwargs 處理任意數量的位置和關鍵字參數。

L) 10. 現實世界用例

  • 日誌記錄: 記錄函數呼叫、參數和傳回值以進行偵錯或審核。
  • 計時: 測量函數的執行時間以進行效能分析。
  • 快取: 儲存昂貴的函數呼叫的結果以避免冗餘計算(記憶)。
  • 驗證與授權: 在執行函數之前驗證使用者憑證或權限。
  • 輸入驗證: 檢查傳遞給函數的參數是否符合特定條件。
  • 速率限制: 控制在特定時間內呼叫函數的次數。
  • 重試邏輯: 如果由於暫存錯誤而失敗,則自動重試函數呼叫。
  • 特定於框架的任務: Flask 和 Django 等框架使用裝飾器進行路由(將 URL 映射到函數)、註冊插件等。

M) Python 裝飾器精選列表

您可以在下面找到 Python 裝飾器的精選清單:

  • 很棒的 Python 裝飾器
  • Python 裝飾器庫

N) 11. 結論

裝飾器是 Python 中一個強大而優雅的功能,它允許您以乾淨和聲明性的方式增強函數和類別。
透過了解原理、最佳實踐和潛在陷阱,您可以有效地利用裝飾器來編寫更模組化、可維護和富有表現力的程式碼。
它們是任何 Python 程式設計師的武器庫中的寶貴工具,特別是在使用框架或建立可重複使用元件時。

以上是Python 裝飾器:綜合指南的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
Python vs. C:了解關鍵差異Python vs. C:了解關鍵差異Apr 21, 2025 am 12:18 AM

Python和C 各有優勢,選擇應基於項目需求。 1)Python適合快速開發和數據處理,因其簡潔語法和動態類型。 2)C 適用於高性能和系統編程,因其靜態類型和手動內存管理。

Python vs.C:您的項目選擇哪種語言?Python vs.C:您的項目選擇哪種語言?Apr 21, 2025 am 12:17 AM

選擇Python還是C 取決於項目需求:1)如果需要快速開發、數據處理和原型設計,選擇Python;2)如果需要高性能、低延遲和接近硬件的控制,選擇C 。

達到python目標:每天2小時的力量達到python目標:每天2小時的力量Apr 20, 2025 am 12:21 AM

通過每天投入2小時的Python學習,可以有效提升編程技能。 1.學習新知識:閱讀文檔或觀看教程。 2.實踐:編寫代碼和完成練習。 3.複習:鞏固所學內容。 4.項目實踐:應用所學於實際項目中。這樣的結構化學習計劃能幫助你係統掌握Python並實現職業目標。

最大化2小時:有效的Python學習策略最大化2小時:有效的Python學習策略Apr 20, 2025 am 12:20 AM

在兩小時內高效學習Python的方法包括:1.回顧基礎知識,確保熟悉Python的安裝和基本語法;2.理解Python的核心概念,如變量、列表、函數等;3.通過使用示例掌握基本和高級用法;4.學習常見錯誤與調試技巧;5.應用性能優化與最佳實踐,如使用列表推導式和遵循PEP8風格指南。

在Python和C之間進行選擇:適合您的語言在Python和C之間進行選擇:適合您的語言Apr 20, 2025 am 12:20 AM

Python適合初學者和數據科學,C 適用於系統編程和遊戲開發。 1.Python簡潔易用,適用於數據科學和Web開發。 2.C 提供高性能和控制力,適用於遊戲開發和系統編程。選擇應基於項目需求和個人興趣。

Python與C:編程語言的比較分析Python與C:編程語言的比較分析Apr 20, 2025 am 12:14 AM

Python更適合數據科學和快速開發,C 更適合高性能和系統編程。 1.Python語法簡潔,易於學習,適用於數據處理和科學計算。 2.C 語法複雜,但性能優越,常用於遊戲開發和系統編程。

每天2小時:Python學習的潛力每天2小時:Python學習的潛力Apr 20, 2025 am 12:14 AM

每天投入兩小時學習Python是可行的。 1.學習新知識:用一小時學習新概念,如列表和字典。 2.實踐和練習:用一小時進行編程練習,如編寫小程序。通過合理規劃和堅持不懈,你可以在短時間內掌握Python的核心概念。

Python與C:學習曲線和易用性Python與C:學習曲線和易用性Apr 19, 2025 am 12:20 AM

Python更易學且易用,C 則更強大但複雜。 1.Python語法簡潔,適合初學者,動態類型和自動內存管理使其易用,但可能導致運行時錯誤。 2.C 提供低級控制和高級特性,適合高性能應用,但學習門檻高,需手動管理內存和類型安全。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

SecLists

SecLists

SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)