修饰符函数语法python

2024-04-26 02:59:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习python中的decorator函数,我的脑子里还想着@语法。你知道吗

下面是一个简单的decorator函数示例,它两次调用相关函数。你知道吗

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

如果我理解正确,似乎:

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

相当于:

print_hi = duplicator(print_hi)
print_hi()

但是,让我们考虑一下,如果我移到一个更复杂的例子。例如,我不想调用函数两次,而是想调用用户定义的次数。你知道吗

举个例子: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

我可以通过以下方式拨打:

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

然而,这肯定不等于:

print_hi = repeat(print_hi)

因为我们有额外的参数num_times。你知道吗

我误解了什么? 是否等同于:

print_hi = repeat(print_hi, num_times=4)

Tags: 函数returndefargsdecoratorhiwrappernum
2条回答

repeat(num_times)返回一个函数,该函数用于修饰print_hi。你知道吗

@repeat(num_times=4)
def print_hi(num_times):
    ...

总计

f = repeat(num_times)
print_hi = f(print_hi)

repeat返回的函数是decorator_repeat,它修饰print_hi。你知道吗

对于repeat修饰符的情况,等价物是:

print_hi = repeat(num_times=4)(print_hi)

这里,repeat接受num_times参数并返回decorator_repeat闭包,它本身接受func参数并返回wrapper_repeat闭包。你知道吗

相关问题 更多 >