【发布时间】:2020-07-24 07:58:57
【问题描述】:
我正在学习装饰器,并遇到了一个装饰器进行参数的示例。不过,这对我来说有点令人困惑,因为我了解到(注意:这个问题的示例 大部分来自this article):
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
相当于
foo = my_wrapper(foo)
所以,对我来说,如何接受参数是没有意义的,为了更好地解释,这是一个接受参数的装饰器示例:
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
所以当我看到这个时,我在想:
greet = repeat(greet, num_times=4)
我知道这是不对的,因为 num_times 是唯一应该通过的参数。那么没有“@-symbol-syntax”的@repeat(num_times=4)的正确等价物是什么?谢谢!
【问题讨论】:
-
有关装饰器是什么的详细说明,请参阅this answer