在类中使用装饰器

2024-04-29 15:51:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试向所需的类方法添加一个装饰器,并为此编写了以下代码。我需要这个来处理所有类似的课程。你知道吗

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

这样做对吗?我在寻找最好的方法。你知道吗

另外,我知道我们可以函数工具.wrapps在修饰函数时保留docstring。当我们布置课堂时,是否需要这样的东西?你知道吗


Tags: 方法selfifdefsteppassmethoddec
1条回答
网友
1楼 · 发布于 2024-04-29 15:51:26

在Satwik Kansal精彩的Metaprogramming in PythonIBM教程中,我发现了以下宝石:

Satwik首先定义了一个装饰器:


from functools import wraps
import random
import time

def wait_random(min_wait=1, max_wait=30):
    def inner_function(func):
        @wraps(func)
        def wrapper(args, **kwargs):
            time.sleep(random.randint(min_wait, max_wait))
            return func(args, **kwargs)

        return wrapper

    return inner_function

然后他创建了一个类包装器,将这个装饰器应用于一个类:

def classwrapper(cls):
    for name, val in vars(cls).items():
        #callable return True if the argument is callable
        #i.e. implements the __call
        if callable(val):
            #instead of val, wrap it with our decorator.
            setattr(cls, name, wait_random()(val))
    return cls

应用程序:


# decorate a function

@wait_random(10, 15)
def function_to_scrape():
    #some scraping stuff

# decorate a class

@classwrapper
class Scraper:
    # some scraping stuff

要在您的案例中使用它,请用您自己的wait_randomdecorator替换它。把你的职能变成一个装饰者。 例如

from functools import wraps
import allure

def apply_allure():
    def inner_function(func):
        @wraps(func)
        def wrapper(args, **kwargs):
            func = allure.step(func)
            return func(args, **kwargs)

        return wrapper

    return inner_function

classwrapper中,用apply_allure替换wait_random

请阅读本教程以获取更多信息和解释

相关问题 更多 >