【发布时间】:2020-07-11 18:40:18
【问题描述】:
在阅读了出色的 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
可以实现为这样的类
class Repeat:
def __init__(self, times):
self.times = times
def __call__(self, fn):
def _wrapper(*args, **kwargs):
for _ in range(self.times):
result = fn(*args, **kwargs)
return result
return _wrapper
但是我似乎无法为optional argument decorator example 找到类解决方案:
def repeat(_func=None, *, num_times=2):
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
if _func is None:
return decorator_repeat
else:
return decorator_repeat(_func)
只有我一个人,还是那个相当邪恶的人? XD 希望看到解决方案!
【问题讨论】: