search

Home  >  Q&A  >  body text

decorator - python中的带参数装饰器可以调用被装饰的函数中的参数不(除了全局变量)

例子:

def lo(func0, *args0, **kwargs0):
    def _wrapper(func):
        def wrapper(*args, **kwargs):
            func(*args, **kwargs)
            func0(*args0, **kwargs0)
        return wrapper
    return _wrapper


def f1(a):
    print a+1

@lo(f1, a)
def f(a):
    print a

f(1)

如何才能让装饰器lo调用函数f的参数a?

PHP中文网PHP中文网2803 days ago879

reply all(1)I'll reply

  • ringa_lee

    ringa_lee2017-04-17 13:09:38

    What are you doing? The a in the decorator call is not defined. I don't quite understand what you want to do, see question X-Y.

    Do you want this?

    def lo(func0):
        def _wrapper(func):
            def wrapper(*args, **kwargs):
                func(*args, **kwargs)
                func0(*args, **kwargs)
            return wrapper
        return _wrapper
    
    def f1(a):
        print(a+1)
    
    @lo(f1)
    def f(a):
        print(a)
    
    f(1)
    

    reply
    0
  • Cancelreply