Decorator Concept & Actual use of dry goods and decoration Concept
Definition:
- Essentially, it is a function (decorated with other functions) that adds additional functions to other functions.
Principles:
- The source code of the decorated function cannot be modified.
- The call method of the decorated function cannot be modified.
Implement the knowledge reserve of the decorator:
- Functions and "variables"
- High-order functions
Decorator = high-order functions + nested Functions
Actual usage:
1 # decorator Test 2 3 import time 4 5 # decorator 6 def adron (fun): 7 print ('memory address for passing in the function to be decorned: % s' % fun) 8 def ad_x (* args, ** kwargs): 9 start_time = time. time () 10 # fun + () method to execute the decorated function 11 fun (* args, ** kwargs) 12 stop_time = time. time () 13 print ('visit world use time: % s' % (stop_time-start_time) 14 return ad_x15 16 # decorated function 17 @ adron # @ adron = adron (tet ), pass the tet memory address as a parameter and pass it to the decorator function 18 def tet (): 19 time. sleep (3) 20 print ('Hello world! ') 21 # After the tet is decorated by the decorator, the memory address is ad_x memory address 22 tet () 23 24 @ adron25 def jsq (n, s ): 26 for I in range (n): 27 time. sleep (s) 28 print (I) 29 30 jsq (5, 0.1)
High-order decorators:
1 # decorator 2 3 name = 'sober' 4 password = '000000' 5 6 def badn (action): 7 print ("Login method: % s" % action) 8 # Pass in 9 def bt_badn (fun): 10 print ('view fun value: % s' % fun) 11 def adron (* args, ** kwargs): 12 if action = 'local': 13 name_value = input ('Please user name: ') 14 password_value = input ('Please Password :') 15 if name = name_value and password = password_value: 16 # fun will execute the decorated function, because the incoming fun is the memory address of the executed function 17 ret_valu E = fun (* args, ** kwargs) 18 print ('return to the frontend after the decoration function is executed in the decorator ') 19 # return the result 20 return ret_value21 else: 22 print ('username or password error') 23 elif action = 'ldap ': 24 print ('ldap is unrealized') 25 # return returns the function name, which is the address in the returned Function Memory, using the memory address + () call function 26 return adron27 return bt_badn28 29 30 def index (): 31 print ('Welcome! Hello world! ') 32 33 @ badn (action = 'local') # @ badn = badn (home) If you want to input parameters, You need to nest 34 def home () in the decorator function (): 35 print ('Welcome home path') 36 return 'A' 37 38 @ badn (action = 'ldap ') 39 def ldap (): 40 print ('Welcome ldap enter') 41 42 index () 43 # The Execution here uses the Function Memory Address + () to execute the function 44 # home () 45 print ('display home Return Value: % s' % home () 46 ldap ()
Note: Learning oldboy python automated O & M-decorator notes
I have added my understanding of decoration in the code.