我正在尝试将可选参数传递给我的 python 类装饰器。在我目前拥有的代码下方:
class Cache(object):
def __init__(self, function, max_hits=10, timeout=5):
self.function = function
self.max_hits = max_hits
self.timeout = timeout
self.cache = {}
def __call__(self, *args):
# Here the code returning the correct thing.
@Cache
def double(x):
return x * 2
@Cache(max_hits=100, timeout=50)
def double(x):
return x * 2
第二个带有覆盖默认装饰器参数的装饰器( max_hits=10, timeout=5
在我的 __init__
函数中)不起作用,我得到了异常 TypeError: __init__() takes at least 2 arguments (3 given)
.我尝试了很多解决方案并阅读了有关它的文章,但在这里我仍然无法使其工作。
有解决这个问题的想法吗?谢谢!
原文由 Dachmt 发布,翻译遵循 CC BY-SA 4.0 许可协议
@Cache(max_hits=100, timeout=50)
调用__init__(max_hits=100, timeout=50)
,所以你不满足function
论点。您可以通过检测函数是否存在的包装方法来实现您的装饰器。如果它找到一个函数,它可以返回 Cache 对象。否则,它可以返回一个将用作装饰器的包装函数。