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.mzph.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; 诸葛亮去…