Skip to main content
 首页 » 编程设计

python之编写一个装饰器,为一个类的所有方法应用另一个带有参数的装饰器

2025年02月15日9telwanggs

来自这个post .接受的答案与不带参数的装饰器配合得很好。我正在尝试扩展此解决方案以使其接受应用装饰器的参数。

详细来说,我有调用外部 api 的函数。因为这些调用经常失败,所以我从这个 library 应用了重试装饰器到所有功能。为了避免为所有函数一次又一次地放置 @retry(...) 行,我决定将它们集中在一个类中。我创建了 RetryClass 并将所有函数作为 classmethod 放在类中。现在,我正在寻找一种为类的所有方法应用 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) 

然而,注释掉类装饰器运行没有错误。有什么我想念的吗?

请您参考如下方法:

问题是 @classmethod 不再是 a() 的顶级装饰器。 RetryClass.a 当前按顺序使用 @classmethod 和 @retry 进行修饰。 RetryClass 等同于:

class RetryClass(object): 
 
    @retry(wait_random_min=100, wait_random_max=300, stop_max_attempt_number=3) 
    @classmethod 
    def a(cls): 
        pass 

您的类(class)需要等同于:

class RetryClass(object): 
 
    @classmethod 
    @retry(wait_random_min=100, wait_random_max=300, stop_max_attempt_number=3) 
    def a(cls): 
        pass