python深入研究_深入研究Python装饰器:第1部分

python深入研究

This is part one of the four-part series on decorators in Python.

这是关于Python装饰器的四部分系列之一。

Decorators are a powerful Python feature for multiple reasons. They allow us to extend the behavior of a Callable[1] without permanently modifying them. They improve readability, maintainability, and thereby productivity. Aside from that, decorators have more practical uses in the modern programmer’s toolbox. You can use them to log functions, which can be helpful when debugging, or to time functions, to see how long it takes a function to execute. These are also examples that will be touched upon in more detail in the next few articles in the this series.

出于多种原因,装饰器是强大的Python功能。 它们使我们可以扩展Callable [ 1 ]的行为,而无需对其进行永久性修改。 它们提高了可读性,可维护性,从而提高了生产率。 除此之外,装饰器在现代程序员的工具箱中还有更多实际用途。 您可以使用它们来记录函数(这在调试时可能会有所帮助)或对函数计时,以查看函数执行所需的时间。 这些也是示例,本系列的下几篇文章将更详细地介绍这些示例。

Decorators can only be used on callables. Callables in Python include Classes, Functions, and Methods [2]. Taking functions as an example, decorators allow us to execute code before and or after the decorated function without directly altering the function itself.

装饰器只能用于可调用对象。 Python中的可调用对象包括类,函数和方法[ 2 ]。 以函数为例,修饰器允许我们在修饰的函数之前或之后执行代码,而无需直接更改函数本身。

As mentioned earlier, It’s important to note that you can use a function as a decorator as is since it is a callable. However, you must make a class callable to use a decorator, as they are not by default [3]. This can be done by adding a __call__() method in the class.

如前所述,需要注意的是,您可以将函数直接用作装饰器,因为它是可调用的 。 但是, 您必须使一个可调用的类才能使用装饰器,因为它们默认情况下不是 [ 3 ]。 这可以通过在类中添加__call__()方法来完成。

Below is an example of a function being decorated.

下面是装饰函数的示例。

@test_decorator
def test_function():
    print('Hello!')

The above code can also be written as:

上面的代码也可以写成:

test_function = test_decorator(test_function) or modified_function = test_decorator(test_function).

test_function = test_decorator(test_function)modified_function = test_decorator(test_function)

In the first instance, the original function is modified. The second case, however preserves the test_function as is. This way, one can use test_function() when you need to, and use modified_function() when appropriate [4].

首先,原始功能被修改。 但是,第二种情况按test_function保留test_function 。 通过这种方式,可以使用test_function()当你需要和使用modified_function()在适当的时候[ 4 ]。

Now, let’s take a look at a more concrete example:

现在,让我们看一个更具体的例子:

def test_decorator(function):
    def innerFunc():
        print("Called before the test_function.")
        function()
        print("Called after the test_function.")
    return innerFunc()


@test_decorator
def test_function():
    print('test_function was called.')

While this may seem more complicated than the last example, it really isn’t. One possible question could be “Why is the innerFunc() being used?". The innerFunc() is being used to wrap the test_function(), by calling it in between the print statements. See the output:

尽管这看起来比上一个示例复杂,但实际上并非如此。 一个可能的问题可能是“为什么是innerFunc()被使用?”的。 innerFunc()被用来包裹test_function()通过调用它在打印语句之间看到的输出:

Called before the test_function.
test_function was called.
Called after the test_function.

As you can see, the decorator is working quite well. Now you could argue that it would take less work to just input the print statements into the test_function(), but in the long run, you can reuse the test_decorator with more ease, and organization. For example:

如您所见,装饰器运行良好。 现在您可能会争辩说,仅将打印语句输入到test_function()中会花费较少的工作,但是从长远来看,您可以更轻松地和组织地重用test_decorator。 例如:

def test_decorator(function):
    def innerFunc():
        print("Called before the function.")
        function()
        print("Called after the function.")
        print('')
    return innerFunc()


@test_decorator
def test_function():
    print('test_function was called.')


@test_decorator
def second_function():
    print('second_function was called.')

Finally, we see the versatility of decorators. Instead of adding more print statements, we simply added @test_decorator to the beginning of the function, which produced the following output:

最后,我们看到了装饰器的多功能性。 无需添加更多的打印语句,我们只需在函数的开头添加@test_decorator即可产生以下输出:

Called before the function.
test_function was called.
Called after the function.


Called before the function.
second_function was called.
Called after the function.

Note: The empty print statement was added to separate the two functions output.

注意:添加了空的print语句以分隔两个函数的输出。

In conclusion, decorators can be used to vastly improve the organization, readability and efficiency of your code. So, next time you see the opportunity to utilize a decorator instead of putting repetitive lines in your function, give it a try. You might just like the feeling of ease it brings. If you liked this article, be on the lookout for part 2 and more in the series. In the next article, we will be covering logging decorators and how to create one. Thanks for reading, and stay tuned for more!

总之,装饰器可用于极大地改善代码的组织,可读性和效率。 因此,下次您发现有机会使用装饰器而不是在函数中放置重复的行时,请尝试一下。 您可能只喜欢它带来的轻松感。 如果您喜欢这篇文章,请关注本系列的第2部分及更多内容。 在下一篇文章中,我们将介绍日志记录装饰器以及如何创建装饰器。 感谢您的阅读,敬请期待!

翻译自: https://medium.com/analytics-vidhya/delving-into-python-decorators-part-1-a95b57d3a7bc

python深入研究

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值