python -- 带有参数的装饰器

1.带有参数的装饰器示例

def decorator(arg1, arg2):
    def real_decorator(func):
        def wrapper(*args, **kwargs):
            print("You decorated a function that does something with %s and %s" % (arg1, arg2))
            func(*args, **kwargs)
        return wrapper

    return real_decorator

@decorator("args1", "args2")
def print_args(*args):
    for arg in args:
        print(arg)


print_args(1, 2, 3)

测试结果

>>> print_args(1, 2, 3)
You decorated a function that does something with args1 and args2
1
2
3
>>> 

2.基于类的装饰器

class MyDecorator(object):
    def __init__(self, func_to_decorate):
        print("init MyDecorator")
        self.func_to_decorate = func_to_decorate

    def __call__(self, *args, **kwargs):
        print("call MyDecorator")
        return self.func_to_decorate(*args, **kwargs)

@MyDecorator
def print_more_args(*args):
    for arg in args:
        print(arg)

print_more_args(1, 2, 3)
print("------------")
print_more_args(1, 2, 3)

测试结果

init MyDecorator
call MyDecorator
1
2
3
------------
call MyDecorator
1
2
3

  

3.带有参数的基于类的装饰器

class MyDecoratorWithParams(object):
    def __init__(self, arg1, arg2):
        print("init MyDecoratorWithParams")
        print(arg1)
        print(arg2)

    def __call__(self, fn, *args, **kwargs):
        print("call MyDecoratorWithParams")

        def new_func(*args, **kwargs):
            print("function has been decorated.")
            return fn(*args,**kwargs)

        return new_func

@MyDecoratorWithParams("arg1", "arg2")
def print_args_again(*args):
    for arg in args:
        print(arg)

print_args_again(1, 2, 3)
print("----------------")
print_args_again(1, 2, 3)

测试结果:

init MyDecoratorWithParams
arg1
arg2
call MyDecoratorWithParams
function has been decorated.
1
2
3
----------------
function has been decorated.
1
2
3

  

原文地址:https://www.cnblogs.com/abclife/p/7462860.html