我正在学习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)
repeat(num_times)
返回一个函数,该函数用于修饰print_hi
。你知道吗总计
repeat
返回的函数是decorator_repeat
,它修饰print_hi
。你知道吗对于
repeat
修饰符的情况,等价物是:这里,
repeat
接受num_times
参数并返回decorator_repeat
闭包,它本身接受func
参数并返回wrapper_repeat
闭包。你知道吗相关问题 更多 >
编程相关推荐