在編程中,裝飾器是一種設計模式,它動態地向對象添加額外的職責。在 Python 中,一個函數是一階對象。 因此,Python 中的裝飾器在不修改函數的情況下,動態地向函數添加額外的責任/功能。
在 Python 中,一個函數可以作為參數傳遞給另一個函數。也可以在另一個函數內部定義一個函數,一個函數可以返回另一個函數。
因此,Python 中的裝飾器是一個接收另一個函數作為參數的函數。參數函數的行為是由裝飾器擴展的,並沒有實際修改它。可以使用@decorator 語法在函數上應用 decorator 函數。
讓我們逐步理解 Python 中的裝飾器。
假設我們有greet()
功能,如下所示。
Example: A Function
def greet():
print('Hello! ', end='')
現在,我們可以通過將上面的函數傳遞給另一個函數來擴展它的功能,而無需修改它,如下所示。
Example: A Function with Argument
def mydecorator(fn):
fn()
print('How are you?')
上圖,mydecorator()
函數以一個函數為自變量。它調用參數函數,還打印一些附加的東西。因此,它擴展了greet()
功能的功能,而沒有對其進行修改。 然而,它並不是真正的裝飾者。
Example: Calling Function in Python Shell
>>> mydecorator(greet)
Hello! How are you?
mydecorator()
不是 Python 中的裝飾器。Python 中的裝飾器可以使用@decorator_function_name
語法在任何適當的函數上定義,以擴展底層函數的功能。
以下定義了上述greet()
功能的裝飾器。
Example: A Decorator Function
def mydecorator(fn):
def inner_function():
fn()
print('How are you?')
return inner_function
mydecorator()
函數是以函數(任何不取任何參數的函數)為參數的裝飾函數。 內部函數inner_function()
可以訪問外部函數的參數,所以它在調用參數函數之前或之後執行一些代碼來擴展功能。 mydecorator
函數返回一個內部函數。
現在,我們可以使用mydecorator
作為裝飾器來應用於不接受任何參數的函數,如下所示。
Example: Applying Decorator
@mydecorator
def greet():
print('Hello! ', end='')
現在,調用上面的greet()
函數會給出如下輸出。
Example: Calling a Decorated Function
>>> greet()
Hello! How are you?
mydecorator
可以應用於任何不需要任何參數的函數。例如:
Example: Applying Decorator
@mydecorator
def dosomething():
print('I am doing something.', end='')
Example: Calling Decorated Function in Python Shell
>>> dosomething()
I am doing something. How are you?
典型的裝飾函數如下所示。
Decorator Function Syntax
def mydecoratorfunction(some_function): # decorator function
def inner_function():
# write code to extend the behavior of some_function()
some_function() # call some_function
# write code to extend the behavior of some_function()
return inner_function # return a wrapper function
內置裝飾器
Python 庫包含許多內置裝飾器,作為定義屬性、類方法、靜態方法等的快捷方式。
裝飾者 | 描述 |
---|---|
@property | 將方法聲明為屬性的 setter 或 getter 方法。 |
@classmethod | 將方法聲明為類的方法,可以使用類名調用該方法。 |
@staticmethod | 將方法聲明為靜態方法。 |
接下來了解內置 decorator @property
。*****
原創文章,作者:VWNXI,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/324617.html