Python修飾器(帶引數的修飾器)
阿新 • • 發佈:2019-02-12
def deco(func): def wrapper(*arg, **kw): print('decorator arg: %s' % arg_of_decorator) print('call %s in decorator' % func.__name__) return func(*arg, **kw) return wrapper @deco def test(): pass #等價於 test=deco(test),即在@修飾器名稱後直接加(被修飾的函式名) #因此,帶引數的修飾器可以如下實現: def decorator(arg_of_decorator): def deco(func): def wrapper(*arg, **kw): print('decorator arg: %s' % arg_of_decorator) print('call %s in decorator' % func.__name__) return func(*arg, **kw) return wrapper return deco @decorator("修飾器引數") def test1(): pass #等價於 test1 = decorator("修飾器引數")(test1) = deco(test1) #修飾器的引數已經傳遞進去