有条件的装饰器实现

时间:2018-05-30 07:06:05

标签: python python-decorators

我想拥有条件装饰器。以下是我的代码: -

def int_decorator(func):  # checks whether the args passed is of type int.
    def wrapper(*args, **kwargs):
        a, b = args
        if not (isinstance(a, int) and isinstance(b, int)):
            return
        return func(*args, **kwargs)
    return wrapper


decorator_mapping = {
    'int': int_decorator
}

class conditional_decorator(object):
    def __init__(self, func):
        self.func = func

    def __call__(self, *args, **kwargs):
        decorator = decorator_mapping.get(kwargs.get('decorator'))
        if not decorator:
            # Return the function unchanged, not decorated.
            return self.func(*args, **kwargs)
        return decorator(self.func(*args, **kwargs))


@conditional_decorator
def func(a, b, *args, **kwargs):
    return(1)

print(func(1, 2, decorator='int'))

我想要的是decorator_mapping中是否存在与func中传递的值相匹配的装饰器,然后对该函数应用相同的装饰器,否则不应用任何装饰器。

当没有任何装饰器时,上面的代码效果很好,但是当找到装饰器时失败。它打印是function的参考。

我哪里错了?

2 个答案:

答案 0 :(得分:2)

def __call__(self, *args, **kwargs):
    decorator = decorator_mapping.get(kwargs.get('decorator'))
    if not decorator:
        # Return the function unchanged, not decorated.
        return self.func(*args, **kwargs)
    return decorator(self.func)(*args, **kwargs)

你想装饰这个函数,然后调用它的装饰版本。

答案 1 :(得分:1)

Decorator接受一个函数,返回一个函数。这一行:

    return decorator(self.func(*args, **kwargs))

应该是:

    return decorator(self.func)(*args, **kwargs)