【发布时间】: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)。其实这很有意义。