在类中使用装饰器

时间:2020-01-05 06:41:15

标签: python python-decorators

我正在尝试将装饰器添加到所需的类方法中,并为此提供了以下代码。我需要使用它来处理所有类似的类。

import allure

def class_method_dec(cls):
    """
    Decorator function to decorate required class methods.
    """
    if cls.method1:
        cls.method1= allure.step(cls.method1)

    if cls.method2:
        cls.method2= allure.step(cls.method2)

    if cls.method3:
        cls.method3= allure.step(cls.method3)

    return cls


@class_method_dec
class TestClass:

    def __init__(self, a, b):
        self.a = a
        self.b = b

    def method1(self):
        """
        method docstring
        """
        pass

    def method2(self):
        """
        method docstring
        """
        pass

    def method3(self):
        """
        method docstring
        """
        pass

这是正确的方法吗?我正在寻找做到这一点的最佳方法。

此外,我了解我们在装饰函数时可以使用functools.wraps保留文档字符串。装饰类时是否需要类似的东西?

0 个答案:

没有答案