新聞中心
在編程中,裝飾器是一種設(shè)計(jì)模式,它動(dòng)態(tài)地向?qū)ο筇砑宇~外的職責(zé)。在 Python 中,一個(gè)函數(shù)是一階對(duì)象。 因此,Python 中的裝飾器在不修改函數(shù)的情況下,動(dòng)態(tài)地向函數(shù)添加額外的責(zé)任/功能。

在 Python 中,一個(gè)函數(shù)可以作為參數(shù)傳遞給另一個(gè)函數(shù)。也可以在另一個(gè)函數(shù)內(nèi)部定義一個(gè)函數(shù),一個(gè)函數(shù)可以返回另一個(gè)函數(shù)。
因此,Python 中的裝飾器是一個(gè)接收另一個(gè)函數(shù)作為參數(shù)的函數(shù)。參數(shù)函數(shù)的行為是由裝飾器擴(kuò)展的,并沒(méi)有實(shí)際修改它??梢允褂聾decorator 語(yǔ)法在函數(shù)上應(yīng)用 decorator 函數(shù)。
讓我們逐步理解 Python 中的裝飾器。
假設(shè)我們有greet()功能,如下所示。
Example: A Function
def greet():
print('Hello! ', end='') 現(xiàn)在,我們可以通過(guò)將上面的函數(shù)傳遞給另一個(gè)函數(shù)來(lái)擴(kuò)展它的功能,而無(wú)需修改它,如下所示。
Example: A Function with Argument
def mydecorator(fn):
fn()
print('How are you?') 上圖,mydecorator()函數(shù)以一個(gè)函數(shù)為自變量。它調(diào)用參數(shù)函數(shù),還打印一些附加的東西。因此,它擴(kuò)展了greet()功能的功能,而沒(méi)有對(duì)其進(jìn)行修改。 然而,它并不是真正的裝飾者。
Example: Calling Function in Python Shell
>>> mydecorator(greet)
Hello! How are you? mydecorator()不是 Python 中的裝飾器。Python 中的裝飾器可以使用@decorator_function_name語(yǔ)法在任何適當(dāng)?shù)暮瘮?shù)上定義,以擴(kuò)展底層函數(shù)的功能。
以下定義了上述greet()功能的裝飾器。
Example: A Decorator Function
def mydecorator(fn):
def inner_function():
fn()
print('How are you?')
return inner_function mydecorator()函數(shù)是以函數(shù)(任何不取任何參數(shù)的函數(shù))為參數(shù)的裝飾函數(shù)。 內(nèi)部函數(shù)inner_function()可以訪問(wèn)外部函數(shù)的參數(shù),所以它在調(diào)用參數(shù)函數(shù)之前或之后執(zhí)行一些代碼來(lái)擴(kuò)展功能。 mydecorator函數(shù)返回一個(gè)內(nèi)部函數(shù)。
現(xiàn)在,我們可以使用mydecorator作為裝飾器來(lái)應(yīng)用于不接受任何參數(shù)的函數(shù),如下所示。
Example: Applying Decorator
@mydecorator
def greet():
print('Hello! ', end='') 現(xiàn)在,調(diào)用上面的greet()函數(shù)會(huì)給出如下輸出。
Example: Calling a Decorated Function
>>> greet()
Hello! How are you? mydecorator可以應(yīng)用于任何不需要任何參數(shù)的函數(shù)。例如:
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? 典型的裝飾函數(shù)如下所示。
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
內(nèi)置裝飾器
Python 庫(kù)包含許多內(nèi)置裝飾器,作為定義屬性、類(lèi)方法、靜態(tài)方法等的快捷方式。
| 裝飾者 | 描述 |
|---|---|
| @property | 將方法聲明為屬性的 setter 或 getter 方法。 |
| @classmethod | 將方法聲明為類(lèi)的方法,可以使用類(lèi)名調(diào)用該方法。 |
| @staticmethod | 將方法聲明為靜態(tài)方法。 |
接下來(lái)了解內(nèi)置 decorator @property。*****
網(wǎng)頁(yè)標(biāo)題:Python中的裝飾器
文章轉(zhuǎn)載:http://fisionsoft.com.cn/article/djojchs.html


咨詢
建站咨詢
