python -- 带有参数的装饰器

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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

  

以上是关于python -- 带有参数的装饰器的主要内容,如果未能解决你的问题,请参考以下文章

python 通用装饰器,带有参数的装饰器,

基于 Python 类的装饰器,带有可以装饰方法或函数的参数

python -- 带有参数的装饰器

Python闭包和装饰器

Python 带有参数的装饰器

python使用上下文对代码片段进行计时,非装饰器