Getting the Python decorators

Overview: python decorator belong to advanced will learn, a lot of people just learning it is difficult to understand, this is easier to understand with a simple way to talk about :( Note: This function requires basic knowledge of)

first step:

We have a function, such as a sum of functions:

def sum_test():
    sum=12+20
    print(sum)

If we need to re-start function before and after printing with the added end for debugging, conventional approaches may be treated to modify this function, as follows:

sum_test DEF (): 
    Print ( "Start calculation ----- -----") 
    SUM = 12 is + 20 is 
    Print (SUM) 
    Print ( "Calculation ----- ----- End")

Before and after the input print () to process

Step two:

If I have more functions need to debug it, you have to modify the original packaged function? One by one to join print, then will be very slow, is there a better way? Yes, you can then define a debugging function, and then go to the function to call is debugging function, as follows:

sum_test DEF (): 
    SUM = 12 is + 20 is 
    Print (SUM) 


DEF pr_test (FUNC): 
    Print ( "Start calculation ----- -----") 
    FUNC () 
    Print ( "End Calculation ----- ----- ") 


IF the __name__ == '__main__': 
    pr_test (sum_test)

The above method pr_test () calls the function sum (), can be modified to avoid duplication, but we pr_test () each pass parameters to give, and this is an easy living, ah, this time to debut a decorator , first came to pr_test () packaged as a decorator:

pr_test DEF (FUNC): 
    DEF out_test (): 
        Print ( "----- counted -----") 
        FUNC () 
        Print ( "----- end computing -----") 
    return out_test 


sum_test DEF (): 
    SUM = 16 + 12 is 
    Print (SUM) 


IF the __name__ == '__main__': 
   RES = pr_test (sum_test) 
   RES ()

 Such a simple decorator to do the work, we just need to call before sum_test defined later sum_test, plus res = pr_test (sum_test), you can achieve the purpose of timing;

   This is the concept of decorators, looks like sum_test is pr_test decorated (there is no function has been renovated feeling that I was a stucco walls, stucco strong ability ah)!

   Our Python provides a syntactic sugar to reduce the amount of input characters. Is @pr_test, used as follows:

pr_test DEF (FUNC): 
    DEF out_test (): 
        Print ( "----- counted -----") 
        FUNC () 
        Print ( "----- end computing -----") 
    return out_test 

@pr_test 
DEF sum_test (): 
    SUM = 16 + 12 is 
    Print (SUM) 


IF the __name__ == '__main__': 
   sum_test ()

  By @pr_test, we completed a decorator function, after any necessary function, you need to add debugging code (can be any public function), then we add this @func in front (corresponding to the function name) on it , they have not grasped the concept of what python decorator?

 

 

 

 

 

Substantial hair is sent to

Guess you like

Origin www.cnblogs.com/limmzz/p/11403308.html