python 裝飾器裝飾類
重點 (Top highlight)
There’s no doubt that Python decorators are one of the more advanced and tougher-to-understand programming concepts. This doesn’t mean you should avoid learning them — as you encounter them in production code sooner or later. This article will help you master the concept in no-time.
毫無疑問,Python裝飾器是更高級,更難理解的編程概念之一。 這并不意味著您應該避免學習它們,因為您遲早會在生產代碼中遇到它們。 本文將幫助您立即掌握這一概念。
This article shouldn’t take you more than 5 minutes to read, maybe 10 if you’re following along with the code. In that time, you’ll get introduced to the concept of decorators starting from the basics — regular Python functions.
本文的閱讀時間不應超過5分鐘,如果您跟隨代碼一起閱讀,則可能需要10分鐘。 到那時,您將從基礎知識(常規的Python函數)開始介紹裝飾器的概念。
Further, the article aims to take your understanding level up step by step, so you don’t get confused in the process. Before jumping into code, we’ll quickly cover what decorators are. Later, towards the end of the article, we’ll cover some benefits and use-cases of decorators, so don’t miss that.
此外,本文旨在逐步提高您的理解水平,因此您不會在此過程中感到困惑。 在進入代碼之前,我們將快速介紹什么是裝飾器。 稍后,在本文結尾處,我們將介紹裝飾器的一些好處和用例,因此請不要錯過。
The middle part is reserved for the concept itself. Let’s start!
中間部分保留給概念本身。 開始吧!
什么是裝飾器? (What are decorators?)
A decorator is a function that takes another function and extends the behavior of the latter function without explicitly modifying it. A Python decorator can make code shorter and more pythonic. It is an advanced topic and can make coding easier once you grasp the concept.
裝飾器是一個函數,它接受另一個函數并擴展后一個函數的行為,而無需顯式修改它。 Python裝飾器可以使代碼更短,更pythonic。 這是一個高級主題,一旦您掌握了這一概念,就可以使編碼變得更容易。
Before we dive deeper, let’s make a quick recap of the basics.
在深入探討之前,讓我們快速回顧一下基礎知識。
裝飾器中使用的功能 (Functions being used in decorators)
Functions are a way of writing a particular code that can be used repeatedly. They exist in almost every programming language and are a huge part of every program.
函數是編寫可以重復使用的特定代碼的方式。 它們幾乎存在于每種編程語言中,并且是每個程序的重要組成部分。
Here’s an example function definition:
這是一個示例函數定義:
def function_name(args):
#code
Now that we know what a function is, the next topic to understand are functions within functions:
現在我們知道了什么是函數,接下來要理解的主題是函數中的函數:
def calc(name='add'):
print('now you are inside the calc() function') def sub():
return 'now you are in the sub() function' def divide():
return 'now you are in the divide() function'
Similar to this, we can also return a function from within another function:
與此類似,我們也可以從另一個函數中返回一個函數:
def calc(name='add'):
print('Now you are in the calc() function') def add():
return 'Now you are in the add() function' def divide():
return 'Now you are in the divide() function' if name == 'add':
return add
else:
return divide
In the above code, we can easily see that with the help of if/else clause we can return function within functions. The last part you need to understand is that a decorator is giving a function as an argument to another function:
在上面的代碼中,我們可以很容易地看到,借助if / else子句,我們可以在函數內返回函數。 您需要了解的最后一部分是,裝飾器將一個函數作為另一個函數的參數:
def welcome():
return 'Welcome to Python!'def do_something_before_welcome(func):
print('Something before executing welcome()')
print(func())
do_something_before_welcome(welcome)Output:
>>> Something before executing welcome()
>>> Welcome to Python!
That’s pretty much all you should know before we dive into decorators. Now the fun part begins.
在我們深入研究裝飾器之前,這幾乎是您應該知道的全部。 現在,有趣的部分開始了。
蒸餾器 (Decorators distilled)
Now we have the required knowledge to understand decorators. Let’s quickly create one:
現在,我們已經具備了了解裝飾器所需的知識。 讓我們快速創建一個:
def my_decorator(func):
def wrapper():
print('Before function call')
func()
print('After function call')
return wrapperdef say_where():
print('say_where() function')
say_where = my_decorator(say_where)Output:
>>> Before function call
>>> say_where() function
>>> After function call
After reading the above example you can hopefully understand decorators better, as we just applied all the basic knowledge of functions covered previously.
閱讀以上示例后,您希望可以更好地了解裝飾器,因為我們剛剛應用了前面介紹的所有功能的基本知識。
Python allows us to use decorators more easily with the @ symbol — sometimes referred to as the pie syntax.
Python允許我們通過@符號(有時稱為Pie語法)更輕松地使用裝飾器。
Let’s see how we can apply it to the above example:
讓我們看看如何將其應用于上面的示例:
def my_decorator(func):
def wrapper():
print('Before function call')
func()
print('After function call')
return wrapper@my_decorator
def say_where():
print('say_where() function')Output:
>>> Before function call
>>> say_where() function
>>> After function call
So, @my_decorator is just an easier way of saying say_where = my_decorator(say_where)
. It’s how you apply a decorator to a function.
因此, @my_decorator只是說say_where = my_decorator(say_where)
一種簡單方法。 這就是將裝飾器應用于函數的方式。
Now we have a clear idea of a python decorator but why do we need them in the first place? Let’s go over some benefits in the next section.
現在我們有了一個清晰的python裝飾器的想法,但是為什么我們首先需要它們呢? 讓我們在下一部分中討論一些好處。
裝飾器-為什么? (Decorators — why?)
We’ve covered the how part of decorators, but the why part may still be a bit unclear to you. That’s why I’ve prepared a couple of real-world decorator use cases.
我們已經介紹了裝飾的如何一部分,但部分原因可能還是有點不清楚你。 這就是為什么我準備了幾個實際的裝飾器用例。
分析,日志記錄和檢測 (Analytics, logging, and instrumentation)
We often need to specifically measure what’s going on, and record metrics that quantify different activities. By summing up such noteworthy events in their closed function or method, a decorator can handle this very specific requirement easily.
我們經常需要專門衡量發生的事情,并記錄量化不同活動的指標。 通過將這些值得注意的事件總結為封閉的函數或方法,裝飾器可以輕松地滿足這一非常特定的要求。
驗證和運行時檢查 (Validation and runtime checks)
For all the pro’s Python type system has, there’s a con. This means some bugs can try to creep in, which more statically typed languages (like Java) would catch at compile time. Looking beyond that, you may want to enforce more sophisticated, custom checks on data going in or out. Decorators can let you easily handle all of this, and apply it to many functions at once.
對于專業人士的所有Python類型系統而言,都有一個缺點。 這意味著一些錯誤可能會嘗試蔓延,而更多的靜態類型語言(如Java)會在編譯時捕獲。 除此之外,您可能希望對進出的數據進行更復雜的自定義檢查。 裝飾器可以讓您輕松地處理所有這些,并將其立即應用于許多功能。
制作框架 (Making Frameworks)
When you ace composing decorators, you’ll have the option to profit by the straightforward syntax of utilizing them, which lets you add semantics to the language that is anything but difficult to utilize. It’s the best thing to have the option to expand the language structure. Numerous well known open source systems utilize this. The web framework Flask utilizes it to course URLs to capacities that handle the HTTP demand.
當您選擇裝飾器時,您可以選擇利用它們的簡單語法來獲利,這使您可以向語言中添加語義,但是很難使用。 最好選擇擴展語言結構。 許多眾所周知的開源系統都利用了這一點。 Web框架Flask利用它來將URL設置為可處理HTTP需求的能力。
I hope these 3 use-cases have convinced you just how important decorators are in real-world tasks. With this, we’ve come to the end of this article. Let’s wrap things up in the next section.
我希望這3個用例能使您確信裝飾器在實際任務中的重要性。 至此,我們到了本文的結尾。 讓我們在下一節中總結一下。
你走之前 (Before you go)
Decorators aren’t such a straightforward concept to understand at first. For me, this concept required multiple readings (and hands-on tasks) to feel confident enough, but it’s all worth it once you get there.
首先,裝飾器并不是一個容易理解的概念。 對我來說,這個概念需要多次閱讀(以及動手操作)才能感到足夠自信,但是一旦到達那里,這一切都是值得的。
So yeah, take your time and don’t rush things. Make sure to understand the functions first, and all the things we’ve covered today. It’s easy to expand from there.
是的,慢慢來,不要著急。 確保首先了解功能,以及我們今天介紹的所有內容。 從那里擴展很容易。
I also want to mention that this was first in a more advanced Python concept series, and topics like generators and parallelism will be covered next. They are also essential for a scalable and clean programming environment, so make sure to stay tuned.
我還要提及的是,這是更高級的Python概念系列中的第一篇,接下來將討論諸如生成器和并行性之類的主題。 它們對于可擴展和干凈的編程環境也是必不可少的,因此請確保隨時關注。
Thanks for reading.
謝謝閱讀。
Join my private email list for more helpful insights.
加入我的私人電子郵件列表以獲取更多有用的見解。
翻譯自: https://towardsdatascience.com/5-minute-guide-to-decorators-in-python-b5ca0f2c7ce7
python 裝飾器裝飾類
本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。 如若轉載,請注明出處:http://www.pswp.cn/news/392271.shtml 繁體地址,請注明出處:http://hk.pswp.cn/news/392271.shtml 英文地址,請注明出處:http://en.pswp.cn/news/392271.shtml
如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!