装饰用参数(装饰工厂)

装饰器只接受一个参数:要装饰的函数。没有办法传递其他参数。

但通常需要其他论点。然后诀窍是创建一个接受任意参数并返回装饰器的函数。

装饰功能

def decoratorfactory(message):
    def decorator(func):
        def wrapped_func(*args, **kwargs):
            print('The decorator wants to tell you: {}'.format(message))
            return func(*args, **kwargs)
        return wrapped_func
    return decorator

@decoratorfactory('Hello World')
def test():
    pass

test()

装饰器想告诉你:Hello World

重要的提示:

有了这样的装饰工厂,你必须用一对括号调用装饰器:

@decoratorfactory # Without parentheses
def test():
    pass

test()

TypeError:decorator() 缺少 1 个必需的位置参数:‘func’

装饰器类

def decoratorfactory(*decorator_args, **decorator_kwargs):
    
    class Decorator(object):
        def __init__(self, func):
            self.func = func

        def __call__(self, *args, **kwargs):
            print('Inside the decorator with arguments {}'.format(decorator_args))
            return self.func(*args, **kwargs)
        
    return Decorator

@decoratorfactory(10)
def test():
    pass

test()

带参数的装饰器里面(10, )