我试图在
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,__init__函数中的timeout = 5)不起作用,我得到异常TypeError:__init __()至少有两个参数(3个给定).我尝试了许多解决方案并阅读有关它的文章,但在这里我仍然无法使其工作.
有什么想法来解决吗?谢谢!
解决方法
@Cache(max_hits = 100,timeout = 50)调用__init __(max_hits = 100,timeout = 50),所以你不满足函数参数.
您可以通过一个检测函数是否存在的包装方法来实现您的装饰器.如果它找到一个函数,它可以返回Cache对象.否则,它可以返回将用作装饰器的包装器函数.
- class _Cache(object):
- def __init__(self,*args):
- # Here the code returning the correct thing.
- # wrap _Cache to allow for deferred calling
- def Cache(function=None,timeout=5):
- if function:
- return _Cache(function)
- else:
- def wrapper(function):
- return _Cache(function,max_hits,timeout)
- return wrapper
- @Cache
- def double(x):
- return x * 2
- @Cache(max_hits=100,timeout=50)
- def double(x):
- return x * 2