允许#方法运行或引发异常的Python装饰器

时间:2016-11-14 20:56:39

标签: python python-decorators

我需要一个装饰器,它接受一个参数并检查(基于一些简单的逻辑)是否应允许该方法运行或引发异常。

class One(obj):
    trend = "trend"
    @myDecorator(self.trend)
    def click_button(self):
        clickable_element = self.driver.find_element_by_id(self.trend)
        clickable_element.click()
        return self


class Two(obj):
    map = "map"

    @myDecorator(self.map)
    def click_button(self):
        clickable_element = self.driver.find_element_by_id(self.map)
        clickable_element.click()
        return self

逻辑应该是这样的:

def my Decorator(arg):
    if arg:
        "run the method"
    else:
        raise "Exception"

3 个答案:

答案 0 :(得分:1)

def parametrised_decorator(parameter):
    def parametrised(function):
        @functools.wraps(function)
        def inner(*args, **kwargs):
            if parameter:
                return function(*args, **kwargs)
            else:
                raise Exception()

        return inner

    return parametrised

答案 1 :(得分:0)

def my_Decorator(arg=None):
    def decorator(func):
        def wrapper(*args, **kwargs):
            if arg:
                return func(*args, **kwargs)

            else:
                raise Exception()

        return wrapper

    return decorator

答案 2 :(得分:0)

from functools import wraps


def my_decorator(f):
    @wraps(f)
    def wrapper(*args, **kwargs):
        if kwargs.pop('runit', None):
            return f(*args, **kwargs)
        else:
            raise Exception()
    return wrapper


@my_decorator
def example():
    print('example')


if __name__ == '__main__':
    # runs function
    example(runit=True)
    # runs exception
    example()