python 装饰器 (多个参数的函数,带参数的装饰器)
最简单的模板是这样的
1 #-*-coding:utf-8-*- 2 3 def outer(func): 4 def inner(): 5 print 'before' 6 func() 7 print 'after' 8 # return r 9 return inner 10 ''' 11 def outer_1(func): 12 def inner(): 13 print 'before 11' 14 func() 15 print 'after 22' 16 # return r 17 return inner 18 19 @outer_1 20 ''' 21 @outer 22 def F1(): 23 print 'test' 24 25 if __name__ == '__main__': 26 F1() 27 ''' 28 运行结果 29 before 30 test 31 after 32 [Finished in 0.1s] 33 '''
--装饰器也能用2个,把注释打开
函数带多个参数,装饰器对应修改以适合多种情况
1 # -*- coding: utf-8 -*- 2 3 from time import ctime 4 from time import sleep 5 6 def ftfunc(func): 7 def timef(*s,**gs): 8 print "[%s] %s() called" % (ctime(),func.__name__) 9 return func(*s,**gs) 10 return timef 11 12 @ftfunc 13 def foo(*s,**gs): 14 print(s) 15 print(gs) 16 17 if __name__ == '__main__': 18 foo() 19 foo(1) 20 foo(1,2) 21 foo(1,2,3) 22 stu = {'name' : 'alam' ,'age' :12} 23 foo(1,2,3,**stu) 24 ''' 25 运行结果 26 [Wed Jun 14 15:49:55 2017] foo() called 27 () 28 {} 29 [Wed Jun 14 15:49:55 2017] foo() called 30 (1,) 31 {} 32 [Wed Jun 14 15:49:55 2017] foo() called 33 (1, 2) 34 {} 35 [Wed Jun 14 15:49:55 2017] foo() called 36 (1, 2, 3) 37 {} 38 [Wed Jun 14 15:49:55 2017] foo() called 39 (1, 2, 3) 40 {'age': 12, 'name': 'alam'} 41 [Finished in 0.1s] 42 43 '''