網頁

2019年4月6日 星期六

Python Decorator

以下將會介紹什麼是Python Decorator以及為什麼要用Python Nested Functions,進一步還會說明Python Decorators的Parameters和Python Pie Syntax,最後解釋何謂Chaining Decorators。



Python Decorator function可以將它的functionality添加到另一個函數但不會修改它,換句話說,Python Decorator包裝了另一個函數,這種行為被稱為metaprogramming,也就是說在編譯時,一部分的程序嘗試修改另一個程序。




1. Python Decorator Function
首先,我們定義一個簡單的函數 hello() 印出“Hello”,現在我們將在Python中定義修飾器函數。 它可以呼叫任何東西; 它不一定是'修飾'。 這是一個更高階的函數,值得注意的是,這些函數的相對順序無關緊要,也就是我們可以在定義 decor() 之前定義 hello(),不會產生任何影響。

def decor(func):

這裡要注意的第一件事是它需要一個函數作為參數。 這是我們想要修飾的函數。 我們想把它稱為func; 你可能想把它叫做別的東西。 在這個函數中,我們nest一個函數,我們稱之為wrap()。 接下來就可以隨意呼叫它。



2. The nested wrap function
在這個函數裡面我們提供了額外的功能,並且還呼叫函數修飾。

def wrap():
         print("NTUCHE")
         func()
         print("NTUCHE")

在這裡print()可以是其他statement,例如像if-block來取代。最後,wrap function傳回decor() function。



3. Assigning and Calling
最後,我們將這個Python裝飾器assaign給一個variable,並將要裝飾的函數作為參數傳遞給裝飾函數。
def hello():
    print("Hello")
newfunc=decor(hello)
newfunc()






newfunc= decor(Hello)

然後,我們在我們分配裝飾器的變量之後使用括號調用該函數

newfunc()

但是,您也可以將其指定給要裝飾的功能本身。 這將重新分配它。 讓我們看一下。

Finally, we assign this Python decorator to a variable and pass the function to be decorated as an argument to the decorating function.

newfunc=decor(sayhello)

Then, we call the function using parentheses after the variable to which we assign the decorators in

python.

newfunc()

However, you can also assign this to the function to be decorated itself. This will reassign it. Let’s see that as well.

4. Why use a Python Nested Function?
為什麼我們要使用wrap函數然後返回它?難道我們不能簡單地在裝飾功能中編寫程式碼嗎? 以下例子會解釋原因。


這裡我們在decor()函式中編寫了額外的功能。 接著我們將其分配給variable。

newfunc=decor(hello)

此時print out是因為decor()呼叫一個函數而不是返回一個值。 當我們使用wrap並且返回它時,我們可以將它儲存在一個variable。 然後我們可以使用該名稱隨時呼叫修飾函式。 現在讓我們調用newfunc()函。

newfunc()


如您所見,由於修飾沒有返回值,因此newfunc=decor(hello)並沒有將修飾函式assign給newfunc,這就是它不可呼叫的原因。



5. Python Decorator with Parameters
到目前為止,我們只在裝飾器加入print statements做修飾,為了了解修飾器如何使用參數,我們將以函式除法為例。 除法的功能就是返回a/b。 但是當我們修飾它時,我們會添加功能來處理b=0的情況。



如果不想列出所有參數,也可以利用*args and **kwargs來傳參數。




6. Pie Syntax in Python
有一種方法可以取代divide=decorator(divide),就是pie syntax;在@符號後面
命名修飾函式,並將其放在要修飾的函式之前。




7. Chaining Decorators in Python
如果使用超過一個Python修飾器來看看如何。




參考
https://data-flair.training/blogs/python-decorator/
https://www.techbeamers.com/python-decorator/?fbclid=IwAR2OUN0biWQuEqEtN_OpMTowycrwH4WDhGTMKCUOtJHdA3Qxgf25Vzf1phE

沒有留言:

張貼留言