A Preliminary Study on python decorators and a preliminary study on python decorations
1. contains a decorator
1 # encoding: UTF-8 2 3 ############ contains a decorator ######### 4 def outer (func ): 5 def inner (* args, ** kwargs): # To decorate f1 (), use these two parameters to accept any parameter, whether f1 defines several parameters 6 print "1" 7 r = func (* args, ** kwargs) # func is used here, do not use f1 8 print "2" 9 return r10 return inner11 12 @ outer # Here outer do not add brackets 13 def f1 (a1, a2 ): 14 print "a1 + a2 =" 15 return a1 + a216 17 f1 (1, 2)
2. There are two (multiple) decorators
1 ########### contains two decorators ########## 2 3 def outer0 (func ): # First 4 def inner (* args, ** kwargs): 5 print "AAAAAAAAA" 6 r = func (* args, ** kwargs) 7 print "bbbbbbbbbb" 8 return r 9 return inner10 11 def outer (func): # second 12 def inner (* args, ** kwargs): # f1 () to be decorated (), these two parameters are used here. You can accept any parameter. No matter how many parameters are defined in f1, 13 print "1" 14 r = func (* args, ** kwargs) # func is used here, do not use the f115 print "2" 16 return r17 return inner18 @ outer0 # decorator. The process is: when f1 () is executed, outer0.inner () and outer0.inner () are executed first (). func calls the inner function of outer, that is, outer. inner () function as the parameter of outer0, 19 # Then outer. inner (). func then calls f1 () 20 @ outer # Here outer should not be enclosed in brackets 21 def f1 (a1, a2): 22 print "a1 + a2 = % d" % (a1 + a2) 23 return 124 25 f1)View Code