【问题标题】:decorator function syntax python装饰器函数语法python
【发布时间】:2018-10-02 10:00:44
【问题描述】:

我正在学习 Python 中的装饰器函数,并且正在研究 @ 语法。

这是一个装饰器函数的简单示例,它调用相关函数两次。

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)

【问题讨论】:

  • 我相信你做对了。
  • repeat(num_times) 返回一个函数,该函数用于装饰print_hi
  • @deco def foo 等价于foo = deco(foo)@deco(args) def foo 等价于foo = deco(args)(foo)。其实这很有意义。

标签: python decorator


【解决方案1】:

对于 repeat 装饰器的情况,等效为:

print_hi = repeat(num_times=4)(print_hi)

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

【讨论】:

    【解决方案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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-17
      • 2014-07-21
      • 2016-07-25
      • 2018-01-28
      • 2019-12-18
      • 2020-07-13
      • 2015-12-10
      相关资源
      最近更新 更多