python 裝飾器裝飾類_5分鐘的Python裝飾器指南

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,一經查實,立即刪除!

相關文章

php中顏色的索引值,計算PHP中兩種顏色之間的平均顏色,使用索引號作為參考值...

我們假設為了討論的目的,每個顏色都有一個“值”.那么,你想要的就足夠簡單:$index 0.2;$val1 get_value_of_color($color1);$val2 get_value_of_color($color2);$newval $val1 * $index $val2 * (1 - $index);$newcolor get_color_from_value($newval);所以,很…

leetcode 989. 數組形式的整數加法

對于非負整數 X 而言,X 的數組形式是每位數字按從左到右的順序形成的數組。例如,如果 X 1231,那么其數組形式為 [1,2,3,1]。 給定非負整數 X 的數組形式 A,返回整數 XK 的數組形式。 示例 1: 輸入:A […

您需要了解的WordPress漏洞以及如何修復它們

by Joel S. Syder喬爾賽德(Joel S.Syder) 您需要了解的WordPress漏洞以及如何修復它們 (WordPress vulnerabilities you need to know about — and how to fix them) WordPress is an incredibly useful and versatile platform for all kinds of blogging. It’s become ver…

Maven基礎。

---恢復內容開始--- Maven: 1、概念。 * maven 是一個項目管理工具。 * maven的作用。 1、jar包。依賴管理。將jar包放在jar包倉庫(pom.xml),不需要每個項目都添加jar包。 2、測試。 3、項目發布。 2、使用。 * 下載解壓即可。 * 環境變量配置…

Dinosaur Run - Dinosaur world Games

轉載于:https://www.cnblogs.com/hotmanapp/p/7092669.html

機器學習實際應用_機器學習的實際好處是什么?

機器學習實際應用Some of my previous introductory posts to machine learning and data science were a bit technical. However, my purpose of this post is to explain some of the practical use-cases of ML solely from a non-technical savvy layman’s perspective w…

Javascript的setTimeOut()和setInterval()的定時器用法

Javascript用來處理延時和定時任務的setTimeOut和setInterval函數應用非常廣泛,它們都用來處理延時和定時任務,比如打開網頁一段時間后彈出一個登錄框,頁面每隔一段時間發送異步請求獲取最新數據等等。但它們的應用是有區別的。 setTimeout()…

php隨機生成車牌號,生成汽車牌照

用戶隨機50選1。好的車牌用戶選不到。我目前的做法是這樣的。所有車牌入庫。別人選了狀態就修改為1。下面是入庫程序,想跟大家討論一下,有沒有更好的方式。use Illuminate\Database\Seeder;class LicensePlatesTableSeeder extends Seeder{public functi…

Go_ go mod 命令解決墻的問題

簡介 由于眾所周知的原因,在下載一些庫的時候會下載不了,比如 golang.org/x/... 相關的庫。為此,網上出現了很多解決方案。 從 Go1.11 開始,Go 引入了 module,對包進行管理,通過 go mod 命令來進行相關操作…

leetcode 1319. 連通網絡的操作次數(并查集)

用以太網線纜將 n 臺計算機連接成一個網絡,計算機的編號從 0 到 n-1。線纜用 connections 表示,其中 connections[i] [a, b] 連接了計算機 a 和 b。 網絡中的任何一臺計算機都可以通過網絡直接或者間接訪問同一個網絡中其他任意一臺計算機。 給你這個…

MySQL中choose標簽的用法

先給大家來個SQL語句&#xff1a; choose (when,otherwize) ,相當于java 語言中的 switch ,與 jstl 中 的 choose 很類似。 <select id"getMemberInfo" resultType"java.util.Map" parameterType"java.util.Map" > SELECT …

php hsetnx,HSETNX命令_視頻講解_用法示例-redis編程詞典-php中文網

set英 [set] 美 [s?t]vt.設置;放置&#xff0c;安置;使處于某種狀況;擺放餐具vi.落山;出發;凝結n.集合;一套&#xff0c;一副;布景;電視機adj.固定的;位于…的;頑固的;安排好的第三人稱單數&#xff1a; sets 復數&#xff1a; sets 現在分詞&#xff1a; setting 過去式&am…

用導函數的圖像判斷原函數的單調性

前言 典例剖析 例1(給定\(f(x)\)的圖像&#xff0c;確定\(f(x)\)的單調性&#xff0c;最簡單層次) 題目暫略。 例2(用圖像確定\(f(x)\)的正負&#xff0c;確定\(f(x)\)的單調性&#xff0c;2017聊城模擬) 已知函數\(yxf(x)\)的圖像如圖所示(其中\(f(x)\)是函數\(f(x)\)的導函數…

樸素貝葉斯 半樸素貝葉斯_使用樸素貝葉斯和N-Gram的Twitter情緒分析

樸素貝葉斯 半樸素貝葉斯In this article, we’ll show you how to classify a tweet into either positive or negative, using two famous machine learning algorithms: Naive Bayes and N-Gram.在本文中&#xff0c;我們將向您展示如何使用兩種著名的機器學習算法&#xff…

python3:面向對象(多態和繼承、方法重載及模塊)

1、多態 同一個方法在不同的類中最終呈現出不同的效果&#xff0c;即為多態。 class Triangle:def __init__(self,width,height):self.width widthself.height heightdef getArea(self):areaself.width* self.height / 2return areaclass Square:def __init__(self,size):sel…

蠕變斷裂 ansys_如何避免范圍蠕變,以及其他軟件設計課程的辛苦學習方法

蠕變斷裂 ansysby Dror Berel由Dror Berel 如何避免范圍蠕變&#xff0c;以及其他軟件設計課程的辛苦學習方法 (How to avoid scope creep, and other software design lessons learned the hard way) 從數據科學的角度來看。 (From a data-science perspective.) You’ve got…

leetcode 674. 最長連續遞增序列

給定一個未經排序的整數數組&#xff0c;找到最長且 連續遞增的子序列&#xff0c;并返回該序列的長度。 連續遞增的子序列 可以由兩個下標 l 和 r&#xff08;l < r&#xff09;確定&#xff0c;如果對于每個 l < i < r&#xff0c;都有 nums[i] < nums[i 1] &a…

深入單例模式 java,深入單例模式四

Java代碼 privatestaticClass getClass(String classname)throwsClassNotFoundException {ClassLoader classLoader Thread.currentThread().getContextClassLoader();if(classLoader null)classLoader Singleton.class.getClassLoader();return(classLoader.loadClass(class…

linux下配置SS5(SOCK5)代理服務

SOCK5代理服務器 官網: http://ss5.sourceforge.net/ yum -y install gcc gcc-c automake make pam-devel openldap-devel cyrus-sasl-devel 一、安裝 # tar xvf ss5-3.8.9-5.tar.gz # cd ss5-3.8.9-5 # ./configure && make && make install 二、修改配置文…

劉備和諸葛亮鬧翻:無意說出蜀國滅亡的根源?

導讀&#xff1a;身為管理者&#xff0c;一件事情&#xff0c;自己做是滿分&#xff0c;別人做是八十分&#xff0c;寧可讓人去做八十分&#xff0c;自己也得跳出來看全局。緊抓大權不放&#xff0c;要么自己干到死&#xff0c;要么是敗于戰略&#xff01;&#xff01; 諸葛亮去…