【发布时间】:2017-07-17 09:55:27
【问题描述】:
来自这个post。接受的答案与不带参数的装饰器很好地配合。我正在尝试扩展此解决方案,使其为应用装饰器提供参数。
详细来说,我有进行外部 api 调用的函数。因为这些调用经常失败,所以我将这个 library 中的重试装饰器应用于所有函数。为了避免为所有功能一次又一次地放置@retry(...) 行,我决定将它们集中在一个类中。我创建了 RetryClass 并将所有函数作为 classmethod 放在类中。现在,我正在寻找一种方法来为类的所有方法应用 retry 装饰器,这样我就可以继续在类中添加新方法,它会自动为新方法应用 retry 装饰器.
注意:重试装饰器接受参数。
@retry(wait_random_min=100, wait_random_max=300, stop_max_attempt_number=3)
这是我的代码:
from retrying import retry
def for_all_methods(decorator):
def decorate(cls):
for attr in cls.__dict__:
if callable(getattr(cls, attr)):
setattr(cls, attr, decorator(getattr(cls, attr)))
return cls
return decorate
@for_all_methods(retry(wait_random_min=100, wait_random_max=300, stop_max_attempt_number=3))
class RetryClass(object):
@classmethod
def a(cls):
pass
def test():
RetryClass.a()
return
这会引发以下错误:
Traceback (most recent call last):
File "/Applications/PyCharm.app/Contents/helpers/pydev/pydevd.py", line 1596, in <module>
globals = debugger.run(setup['file'], None, None, is_module)
File "/Applications/PyCharm.app/Contents/helpers/pydev/pydevd.py", line 974, in run
pydev_imports.execfile(file, globals, locals) # execute the script
File "/Users/gyoho/Datatron/Dev/class-decorator/main.py", line 26, in <module>
test()
File "/Users/gyoho/Datatron/Dev/class-decorator/main.py", line 22, in test
RetryClass.a()
TypeError: unbound method a() must be called with RetryClass instance as first argument (got nothing instead)
但是,注释掉类装饰器运行没有错误。我有什么遗漏吗?
【问题讨论】:
-
当你想将它应用到所有方法时,你最好使用meta class。
标签: python python-2.7 python-decorators