装饰器函数语法python [英] decorator function syntax python

查看:42
本文介绍了装饰器函数语法python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习python中的装饰器函数,并且用@语法包裹了我的头.

I am learning decorator functions in python and I am wrapping my head around the @ syntax.

这是装饰器函数的简单示例,该函数两次调用相关函数.

Here is a simple example of a decorator function which calls the relevant function twice.

def duplicator(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        func(*args, **kwargs)
        func(*args, **kwargs)
    return wrapper

如果我理解正确,则可能会出现:

If I understand correctly, it appears that:

@duplicator
def print_hi():
    print('We will do this twice')

等效于:

print_hi = duplicator(print_hi)
print_hi()

但是,让我们考虑一下我是否要介绍一个更复杂的示例.例如.而不是两次调用该函数,而是要以用户定义的次数调用它.

However, let's consider if I move to a more complex example. E.g. instead of calling the function twice, I want to call it a user-defined amount of times.

使用此处的示例: https://realpython.com/primer-on-python-decorators/

def repeat(num_times):
    def decorator_repeat(func):
        @functools.wraps(func)
        def wrapper_repeat(*args, **kwargs):
            for _ in range(num_times):
                value = func(*args, **kwargs)
            return value
        return wrapper_repeat
    return decorator_repeat

我可以通过以下方式致电:

I can call this via:

@repeat(num_times=4)
def print_hi(num_times):
    print(f"We will do this {num_times} times")

但是,这肯定不等同于:

However, this is most certainly not equivalent to:

print_hi = repeat(print_hi)

因为我们有额外的参数 num_times .

Because we have the extra argument of num_times.

我误会什么?等同于:

print_hi = repeat(print_hi, num_times=4)

推荐答案

对于 repeat 装饰器,等效项是:

For the case of the repeat decorator, the equivalent is:

print_hi = repeat(num_times=4)(print_hi)

此处, repeat 接受一个 num_times 个参数,并返回 decorator_repeat 闭包,该闭包本身接受一个 func 个参数并返回 wrapper_repeat 闭包.

Here, repeat takes a num_times argument and returns the decorator_repeat closure, which itself takes a func arguments and returns the wrapper_repeat closure.

这篇关于装饰器函数语法python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆