作者:aaaaaa师太_667 | 来源:互联网 | 2022-12-03 12:32
我正在学习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)
bruno desthu..
7
对于repeat
装饰器的情况,等效的是:
print_hi = repeat(num_times=4)(print_hi)
这里,repeat
接受一个num_times
参数并返回decorator_repeat
闭包,闭包本身接受一个func
参数并返回wrapper_repeat
闭包.
1> bruno desthu..:
对于repeat
装饰器的情况,等效的是:
print_hi = repeat(num_times=4)(print_hi)
这里,repeat
接受一个num_times
参数并返回decorator_repeat
闭包,闭包本身接受一个func
参数并返回wrapper_repeat
闭包.
2> khelwood..:
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
.