【发布时间】:2011-11-21 11:12:35
【问题描述】:
我正在尝试将可选参数传递给我在 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)。我尝试了许多解决方案并阅读了有关它的文章,但在这里我仍然无法使其工作。
有解决这个问题的办法吗?谢谢!
【问题讨论】:
标签: python arguments decorator