• 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
    

      

  • 相关阅读:
    FlowNet2.0论文笔记
    LeetCode NO477.汉明距离总和
    自然语言的分词方法之N-gram语言模型
    C++函数模板及其实例化和具体化
    Vue2源码解读(5)
    Vue2源码解读(4)
    Vue2源码解读(3)
    Vue2源码解读(2)
    Vue2源码解读(1)
    vue的双向绑定原理及实现
  • 原文地址:https://www.cnblogs.com/abclife/p/7462860.html
Copyright © 2020-2023  润新知