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.

谢谢阅读。

翻译自: https://towardsdatascience.com/5-minute-guide-to-decorators-in-python-b5ca0f2c7ce7

python 装饰器装饰类

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值