Python类装饰器参数

前端之家收集整理的这篇文章主要介绍了Python类装饰器参数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图在 python中将可选参数传递给我的类装饰器.
在我现在的代码下面
  1. class Cache(object):
  2. def __init__(self,function,max_hits=10,timeout=5):
  3. self.function = function
  4. self.max_hits = max_hits
  5. self.timeout = timeout
  6. self.cache = {}
  7.  
  8. def __call__(self,*args):
  9. # Here the code returning the correct thing.
  10.  
  11.  
  12. @Cache
  13. def double(x):
  14. return x * 2
  15.  
  16. @Cache(max_hits=100,timeout=50)
  17. def double(x):
  18. 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对象.否则,它可以返回将用作装饰器的包装器函数.

  1. class _Cache(object):
  2. def __init__(self,*args):
  3. # Here the code returning the correct thing.
  4.  
  5. # wrap _Cache to allow for deferred calling
  6. def Cache(function=None,timeout=5):
  7. if function:
  8. return _Cache(function)
  9. else:
  10. def wrapper(function):
  11. return _Cache(function,max_hits,timeout)
  12.  
  13. return wrapper
  14.  
  15. @Cache
  16. def double(x):
  17. return x * 2
  18.  
  19. @Cache(max_hits=100,timeout=50)
  20. def double(x):
  21. return x * 2

猜你在找的Python相关文章