我试图将可选参数传递给我的类装饰器在python中。 下面的代码我目前有: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
第二个装饰用的参数覆盖(在我__init__
功能max_hits=10, timeout=5
)默认的,不工作,我得到异常TypeError: __init__() takes at least 2 arguments (3 given)
。我尝试了很多解决方案,并阅读了关于它的文章,但在这里我仍然无法完成工作。
任何想法解决这个?谢谢!
感谢你们和@lunixbochs的解决方案!像一个魅力工作:) – Dachmt
如果开发人员用位置而不是关键字参数调用'Cache'(例如'@Cache(100,50)'),那么'function'将被分配值100和'max_hits' 50.一个在调用该函数之前不会引发错误。这可以被认为是令人惊讶的行为,因为大多数人期望统一的位置和关键字语义。 – unutbu