def outer(func): def inter(): print('befor') func() print('after') return inter @outer def f1(): print('F1')
结构:@+函数名
功能:
1.遇到@时自动执行outer函数,并将其下面的函数f1()当做参数传递到装饰器
2.将outer的返回值,重新赋给f1()
有返回值的装饰器
#有返回值的装饰器 def outer(func): def inner(): print('befor') r = func() print('after') return r return inner @outer def f1(): print('F1') return "ff" r = f1() print(r)
带参数的装饰器
def outer(func): def inner(a): print('befor') r = func(a) print('after') return r return inner @outer def f1(args): print(args) return "ff" r = f1('zhang') print(r)
万能参数
def outer(func): def inner(*args, **kwargs): print('befor') r = func(*args, **kwargs) print('after') return r return inner