Learning Python - decorator decorator

Decorator

Definition: essentially a function to add additional functionality to the other functions.

Principle: 1, does not modify the source code of the original function

   2, can not be invoked to modify the way the original function

Important to understand:

   1, a function that is "variable"

   2, higher-order functions: a.

           b return value contains the name of the function

   3, nested functions: 

Warm-up: feel the Python interpreter

__author__ = ' JCX ' 

DEF foo ():
     Print ( " in at The foo " ) 
    bar ()   # interpreter in order to explain, after the first statement Print bar 
 
DEF bar ():
      Print ( " in at The bar " ) # find the bar, the definition 
 
foo () # as long as you can before calling the statement
1 Output:
2 in the foo
3 in the bar

 

application:

1, the print execution time

 1 __author__ = 'jcx'
 2 
 3 import time
 4 
 5 def timer(func): #timer(test1)  func = test1
 6     def deco(*args, **kwargs):
 7         start_time = time.time()
 8         func(*args, **kwargs)
 9         stop_time = time.time()
10         print("Func RunTime = %s" % (stop_time - start_time))
11     return deco
12 
13@timer        # equal to this assignment made Timer = test1 (test1) 
14  DEF test1 ():
 15      the time.sleep (0.1 )
 16      Print ( " in The test1 " )
 . 17  
18 is  @timer
 . 19  DEF test2 (name, Age):    # test2 = Timer (test2) test2 () = Deco () 
20 is      Print ( " test2: " , name, Age)
 21 is  
22 is test1 ()   # actually performing Deco () 
23 is test2 ( " JCX " , 24) # strip parameters 
24

Output:

1 in the test1
2 Func RunTime = 0.10228705406188965
3 test2: jcx 24
4 Func RunTime = 2.09808349609375e-05

 

Guess you like

Origin www.cnblogs.com/jcxioo/p/11580912.html