Python 3.x study notes 5 (decorator), python3.x
1. decorator:
In essence, it is a function. (describe other functions) is to add additional functions to other functions.
Principles:
1) the source code of the decorated function cannot be modified.
2) The call method of the decorated function cannot be modified.
2. Implement the knowledge reserve of the decorator:
1) a function is a variable"
2) Higher-Order Functions
A. pass a function as a real parameter to another function (the function can be added without modifying the source code of the decorated function)
B. the return value contains the function name. (do not modify the function call method)
3) nested Functions
3. High-Order Function + nested function =
4. Initial decorator
import timedef timer(func): #timer(test1) func = test1 def deco(): start_time = time.time() func() #run test1 stop_time = time.time() print('the func run time is %s'%(stop_time-start_time)) return deco@timer #test1 = timer(test1)def test1(): time.sleep(3) print('in the test1')test1()
5. Decorative device with complete functions
User, passwd = 'hsj', '000000' def auth (auth_type): print ('auth func: ', auth_type) def outer_wrapper (func): def wrapper (* args, ** kwargs): print ('wrapper: ', * args, ** kwargs) if auth_type = 'local': username = input ('username :'). strip () password = input ('password :'). strip () if username = user and password = passwd: print ('\ 033 [32; 1 mUser has pass authentication \ 033 [0m') return func (* args, ** kwargs) # from home # else: exit ('\ 033 [31; 1 mInvalid username or password \ 033 [0m') returned by the wrapper Function ') elif auth_type = 'ldap ': print ('ldappppppppppp') return wrapper return outer_wrapperdef index (): print ('Welcome to index psge') @ auth (auth_type = 'local ') # adding parentheses is equivalent to running outer_wraper, so the content # home = auth (home) def home (): print ('Welcome to home page') will be executed ') return 'from home' # Here, the returned value should also have a return value in the decorator. Otherwise, @ auth (auth_type = 'ldap ') def bbs () cannot be returned (): print ('Welcome to bbs page') index () print (home () bbs ()