python 装饰器
一、无参数,无返回值的装饰器
1 def check(func): 2 def inner(): 3 print('def') 4 func() 5 return inner 6 7 @check #foo = check(foo) 8 def foo(): 9 print('abc') 10 11 foo()
二、2个装饰器
1 # -*- coding:utf-8 -*- 2 3 def check(func): 4 def inner(): 5 print('def') 6 func() 7 return inner 8 9 def check1(func): 10 def inner(): 11 print('ghk') 12 func() 13 return inner 14 15 @check #foo = check(foo) 后装饰,先执行 16 @check1 #foo = check1(foo) 先装饰,后执行 17 def foo(): 18 print('abc') 19 20 foo()
结果:
1 def 2 ghk 3 abc
三、带参数,无返回值函数的装饰器
1 # -*- coding:utf-8 -*- 2 3 def check(func): 4 def inner(arg): 5 print('def') 6 func(arg) 7 return inner 8 9 @check #foo = check(foo) 10 def foo(arg): 11 print('abc%s' % arg) 12 13 foo('d')
四、带参数,带返回值函数的装饰器
1 # -*- coding:utf-8 -*- 2 3 def check(func): 4 def inner(arg): 5 print('def') 6 ret = func(arg) 7 print('ghk') 8 return ret 9 return inner 10 11 @check #foo = check(foo) 12 def foo(arg): 13 print('abc%s' % arg) 14 return 'ok' 15 16 ret = foo('d') 17 print(ret)
五、通用的装饰器
1 # -*- coding:utf-8 -*- 2 3 def check(func): 4 def inner(*args, **kwargs): 5 print('...') 6 ret = func(*args, **kwargs) 7 print('---') 8 return ret 9 return inner 10 11 @check #foo = check(foo) 12 def foo(arg): 13 print('abc%s' % arg) 14 return 'ok' 15 16 ret = foo('d') 17 print(ret)
六、装饰器带参数
1 # -*- coding:utf-8 -*- 2 3 def outter(arg): 4 def check(func): 5 def inner(*args, **kwargs): 6 print(arg) 7 print('...') 8 ret = func(*args, **kwargs) 9 print('---') 10 return ret 11 return inner 12 return check 13 14 @outter('e') #先执行outter('e'),再装饰foo = check(foo) 15 def foo(arg): 16 print('abc%s' % arg) 17 return 'ok' 18 19 ret = foo('d') 20 print(ret)
结果:
1 e 2 ... 3 abcd 4 --- 5 ok