Higher order function + nested function = = Adorner
What is an adorner: it's actually a function.
Function: Add additional functions for other functions
Principle: Cannot modify the source code and calling method of the decorated function
Before learning the adorner, you must first understand the following 3 items:
1: function is "variable" (what does that mean, a function that we define, where the function name is a variable and the function body is the data stored in memory).
def foo (): #函数名就相当于变量
Print (' test ') #函数体就相当于内容
Similar to: x (variable) = 1 (content)
The content is actually stored in memory, and the variable is equivalent to the house number (mapped memory content).
Instance
def foo ():
Print (' In the Foo ')
Bar ()
def bar ():
Print (' In the Bar ')
Foo ()
2: higher-order functions
Condition 1: Pass a function name as an argument to another function (add additional functionality to it without modifying the source code of the decorated function)
Example: When calling the execution function fun1, the bar function is passed as an argument, and the parameter is executed within the FUN1 function fun (), Bar->bar ()
def bar ():
Print (' In the Bar ')
def fun1 (fun):
Print (' Start) #进行装饰
Fun () #执行的核心函数
Print (' End ') #进行装饰
FUN1 (BAR)
Condition 2: The return value of the function contains a n>0 function. (Do not modify the function's invocation mode)
Example:
def bar ():
Time.sleep (3)
Print (' In the Bar ')
def test2 (func):
Print (func)
return func
Bar = test2 (bar)
Bar () #这里就是源函数被修饰后, called again to return the modified result
3: Nested function: A function body creates another function, the outermost function is equivalent to a global variable, and all functions inside the function are equivalent to local variables, valid only at the local scope.
Example:
def foo (): #这里相当于全局变量
Print (' In the Foo ')
def bar (): # This is equivalent to a local variable, valid only at the local scope.
Print (' In the Bar ')
Bar () #执行局部变量
Foo () #执行函数调用
Adorner instance 1: Load the timer function body into memory first, then @timer equivalent to pass the Test1 function as an argument to the timer function, and finally call the Test1 () function, which is equivalent to executing the Warpper function within the timer function, returning the internal execution result To Test1
1 defTimer (func):#func = test12 defwarpper ():3Start_time =time.time ()4 func ()5End_time =time.time ()6 Print('The function time is %s'% (stop_time-start_time)7 returnWarpper ()8@timer#Test1=timer (test1)9 deftest1 ():TenTime.sleep (3) One Print('In the test') ATest1 ()#here test1 is equivalent to executing the Warpper functionView Code
Adorner instance 2 with parameters
1 Import Time2 defTimer (fun):#Pass in each decorated function name3 defBar (*args,**kwargs):#Pass in each decorated function parameter4Start =time.time ()5Fun (*args,**Kwargs)6End =time.time ()7 Print('time:%s'% (end-start))8 returnBar9 @timerTen deftest1 (): OneTime.sleep (1) A Print('In the test1') - @timer - deftest2 (name,age): the Print('test2:', Name,age) - test1 () -Test2 ('Jeck', age=22)View Code
Adorner-supplement: How to return the returned value of the decorated function
1USER,PASSWD ='Jeck','abc123'2 defAuth (func):3 defWarpper (*args,**Kwargs):4Username = input ('username')5Password = input ('Password')6 ifUsername = = User andPassword = =passwd:7 Print('user has passwd authentication')8Mess = Func (*args,**kwargs)#This returns the return value of the Func function.9 returnMess#This returns the value of mess to WarpperTen Else: OneExit'Error Password') A returnWarpper#returns the Warpper value that contains the mess - - defindex (): the Print('Welcome to Index page') - @auth - defHome (): - Print('Welcome to Home Page') + return 'From home' #How return here is returned through the adorner - @auth + defBBS (): A Print('Welcome to BBS page') at index () - Print(Home ())#here to print using the value returned by return -BBS ()View Code
Decorator-Advanced version, here to let the above example home with common authentication, BBS with LDAP authentication
1 Import Time2Name,pwd ='Jeck','123'3 defAuth_type (Auth_type):#Authentication Mode parameter passed in4 defAuth (fun):5 defWarpper (*args,**Kwargs):6 ifAuth_type = ='Local':#perform functions According to authentication mode7Name = input ('Name:')8passwd = input ('passwd:')9 ifName = = Name andpasswd = =pwd:Ten Print('Welcome logname:%s'%name) OneContent = Fun (*args,**Kwargs) A returncontent - elifAuth_type = ='LDAP':#perform functions According to authentication mode - Print('LDAP') theContent = Fun (*args,**Kwargs) - returncontent - returnWarpper - returnAuth + defindex (): - Print('Welcome to Index page') +@auth_type (Auth_type ='Local')#increased selection of authentication modes A defHome (): at Print('Welcome to Home Page') - return 'From home' #need to get return back here -@auth_type (Auth_type ='LDAP')#increased selection of authentication modes - defBBS (name,age): - Print('Welcome to BBS page') - returnName,age in index () - Print(Home ()) to Print(BBS ('Bard', age=22))View Code
Python--Decorators