没有语法糖的带参数的装饰器相当于什么?

Tha*_*Guy 5 python python-decorators

我正在学习装饰器,并遇到了一个装饰器争论的例子。不过,这对我来说有点困惑,因为我了解到(注意:这个问题的例子 主要来自这篇文章):

def my_decorator(func):
  def inner(*args, **kwargs):
    print('Before function runs')
    func(*args, **kwargs)
    print('After function ran')
  return inner

@my_decorator
def foo(thing_to_print):
  print(thing_to_print)

foo('Hello')
# Returns:
# Before function runs
# Hello
# After function ran
Run Code Online (Sandbox Code Playgroud)

相当于

foo = my_wrapper(foo)
Run Code Online (Sandbox Code Playgroud)

所以,对我来说,有些东西如何接受参数是没有意义的,为了更好地解释,这是一个接受参数的装饰器示例:

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 greet(name):
    print(f"Hello {name}")

greet('Bob')
# Returns:
# Hello Bob
# Hello Bob
# Hello Bob
# Hello Bob
Run Code Online (Sandbox Code Playgroud)

所以当我看到这个时,我在想:

greet = repeat(greet, num_times=4)
Run Code Online (Sandbox Code Playgroud)

我知道这不可能是正确的,因为这num_times是唯一应该通过的论点。那么@repeat(num_times=4)没有“ @-symbol-syntax”的正确等价物是什么?谢谢!

iz_*_*iz_ 5

在这种情况下,它将是:

greet = repeat(num_times=4)(greet)
Run Code Online (Sandbox Code Playgroud)

这可以解释其中的两层嵌套repeat(您可以说您需要调用该函数“两次”)。repeat(num_times=4)返回一个装饰器,然后该装饰器环绕greet


小智 3

那篇文章让我了解了关于装饰器的一切!这个棒极了。关于非@符号语法的样子:

您可以想象实际的装饰器函数是decorator_repeat(func)中的函数repeat(num_times=4)

@repeat(num_times=4)返回一个装饰器,本质上@decorator_repeat只是@decorator_repeat现在可以访问变量num_times

本文的页面下方显示了如何使这些参数成为可选的,这可能有助于您进一步阐明它。