Decorator--First Understanding

Posted by phamenoth on Sat, 18 May 2019 13:53:00 +0200

Order of function calls

Similar to other languages. python functions are not allowed to be referenced and invoked until they are declared.

 1. Calls or references will report errors before they are declared.
 2 def t1():
 3     print('This is t1...')
 4     t2()
 5 
 6 t1()
 7 
 8 def t2():
 9     print('This is t2...')
10 
11     
12 Display results:
13 This is t1...
14 Traceback (most recent call last):
15 File "D:/Software/pychar/data/s13/practise1.py", line 37, in <module>
16     t1()
17 File "D:/Software/pychar/data/s13/practise1.py", line 35, in t1
18     t2()
19 NameError: name 't2' is not defined
20 
21 
22 
23.2. Correct order of call: (declare function first, refer to or call)
24 def t1():
25     print('This is t1...')
26     t2()
27 
28 def t2():
29     print('This is t2...')
30 
31 t1()
32 
33 display results:
34 This is t1...
35 This is t2...

 

 

Functions and Functions of Functions

You need to add a print log function.
When no function is learned, print can only be displayed, for example:

1 def t1():
2     pass
3     print('logging')
4    
5 def t2():
6     pass
7     print('logging')

 

After learning a function, you can define a function, for example:

def logger(): 
    print('logging')

def t1():
    pass
   logger()   #Direct call function
   
def t2():
    pass
    logger()

 

Functions and Characteristics of Decorators

Additional functionality is required for code that is already online:

Question:
1. There are many lines of code, so it's very troublesome to find them one by one, and add new functions to them.
2. The code has been put on line. Modification of the source code may lead to unknown failures. (Additional functionality is not allowed to modify the source code)
3. The code has been put on line, and the code without light source can not be modified freely, even the way of function call can not be modified freely.

Solution: Use decorator to decorate code.

 

Overview of Decorators

Definition:

Decorator itself is a function, following the declaration, reference, invocation, scope and other relevant rules of function.

II. Role:

Decorator: The purpose is to add additional functions to other functions.

Purpose:

Decorator: The most common uses are user login and authority authentication.

IV. Principles:

1. The source code of the decorated function cannot be modified.
2. It is not possible to modify the way the decorated function is called.
3. The decorator is completely transparent to the decorated function. (Source code does not perceive the existence of decorator functions, but decorator functions do affect source code)
 
 
5. Calling methods:
@+ The function name of the decorator;
A primitive function body can call multiple decorators in the following order of execution:

 

 

Knowledge Reserve of Decorators

1. Functions are "variables"
2. Higher-order functions.
3. Nested function.
Ultimately: higher-order function + nested function ="decorator function

 

Knowledge Point 1: Function is "Variable":

Defining an x or Y is to declare a memory block in memory and assign it to x or y by memory address. When invoking x or y, it can be loaded into the memory block for reference or invocation.

The principle of defining a function of test is the same as above.

The same is true for defining an anonymous body of functions.

Be careful:
The interpreter first reclaims the memory block occupied by the nameless body of the function (that is, the function module of lambda)
del does not delete the memory block, but deletes the name of the memory definition directly, and clears the memory block through the parser.

 

 

Knowledge Point 2. Higher Order Functions:

One of the following two conditions is the higher order function.
A: Pass a function name as an argument to another function, that is, a function as a parameter to another function (add functionality without modifying the source code of the decorated function)
b: The return value contains the name of the function, that is, the return value of the function contains n functions, n > 0 (without modifying the way the function is called)

Practice a:

 1 #!/usr/bin/env python
 2 # -*- coding:utf8 -*-
 3 # Author:Dong Ye
 4 
 5 import time
 6 
 7 #Define a source code. Decoration is required without changing source code and invocation mode:
 8 def bar():   #Define a variable to simulate the function body on the line
 9     time.sleep(3)
10     print("in the bar")
11 
12 
13 #Decorate with higher-order functions bar Code
14 def test1(func):    #Define a parameter for receiving calls test1 The argument of a function, if the name of the function is passed in, then the function has been applied.
15     start_time =  time.time()
16     func()         #call bar Function, similar to x=1,y=x  display y. and func = bar,Direct call func
17     stop_time = time.time()
18     print("the func run time is %s (non bar run time)" %(stop_time-start_time))
19 
20 test1(bar)  #Call the mock decorator to pass arguments to test1(Functions that simulate online environments)
A function is passed into another function as a parameter.
Emphasis: Combining the two important characteristics of decoration, do an exercise 1:
1. The source code of the decorated function cannot be modified.
2. It is not possible to modify the way the decorated function is called.
 
Question:
1. The decorator did not modify the source bar
2. Because test1(bar) changes the way of calling functions, it does not meet the requirements of the decorator.
 
Notes:
The difference between test1(bar) and test1 (bar ():
Tes1 (bar): The memory address is passed to the test1 function by argument as a parameter.
Tes1 (bar (): The function body in memory is passed to the test1 function by argument as a parameter.

 

Exercise b: The return value contains the function name. (without modifying the way functions are called)

 1 #!/usr/bin/env python
 2 # -*- coding:utf8 -*-
 3 # Author:Dong Ye
 4 '''
 5 import time
 6 
 7 #Define a source code. Decoration is required without changing source code and invocation mode:
 8 def bar():   #Define a variable to simulate the function body on the line
 9     time.sleep(3)
10     print("in the bar")
11 
12 
13 #Decorate bar code with higher-order functions
14 def test1(func):    #Define a parameter that receives arguments that call the test1 function. If the name of the function is passed in, the function has been applied.
15     start_time =  time.time()
16     func()         #Call the bar function, similar to x=1,y=x to display y. And func = bar, call func directly
17     stop_time = time.time()
18     print("the func run time is %s (non bar run time)" %(stop_time-start_time))
19 
20 test1(bar)  #Call the mock-up decorator to pass arguments to test1 (a function that simulates the online environment)
21 
22 '''
23 
24 import time
25 
26 #Define analog online code
27 def bar():
28     time.sleep(3)
29     print('in the bar')
30 
31 
32 #Decorator with Higher Order Function
33 def test2(func):
34     print(func) #Printing bar Memory address
35     return func  #Return test2 Running Result Address
36 
37 #Call mode 1: Show the return value
38 print(test2(bar))
39 
40 #Call mode 2: Get the return value
41 t = test2(bar)
42 print(t)
43 #Notes:
44 #First of all, test2 Function to bar Spread to test2 In the function, and then print bar The memory address of the function.
45 #Second, will bar Memory address return Return to t. 
46 #Last, Print t Received bar Address.
47 
48 #Call mode three: variable name override
49 bar = test2(bar) #Return the decorator bar()Memory address, overwriting the original function bar
50 bar()  #Initial function call mode
51 
52 #Notes:
53 #Because bar It has been defined in the source code.
54 #In order not to affect the way source code functions are called, only extract bar Memory Address for Initial Passing Arguments
55 #When the function of the decorator function is executed, the bar Memory address is returned and reassigned to variables
56 #Finally, from the point of view that the original function is called, there is no change. bar()The mode of invocation,
57 # It's returned on the original basis with a decorator. bar The memory value is assigned a second time.
58 #In this way, the decorator function can not only integrate perfectly with the source code, but also satisfy the method of calling function without modifying the source code.

 

 

Knowledge Point 3. Nested Functions:

Creating another function in a function body is called a built-in function (python-based support for static nested fields)

 1 #Nested function:
 2 #Concept: In the body of a function, use def To declare a subfunction
 3 #Action: Higher-order functions+Nested function=Decorator
 4 def foo():
 5     print('in the foo')
 6     def bar():
 7         print('in the bar')
 8 
 9     #In call bar Functions, just like calling local variables, can only be called internally
10     bar()
11 foo()
12 
13 
14 
15 #Access order of local scope and global scope:
16 x = 0
17 def grandpa():
18     #x = 1
19     def dad(): #It's equivalent to defining a variable and doing nothing if you don't call it.
20         x = 2
21         def son():
22             x = 3
23             print(x)  #This value should be 3, because it is only defined in son In this body of functions
24 
25         son()  #If you don't call it, you won't show 3, because nested functions are searched layer by layer.
26     dad()  #If the above definition is not invoked here, nothing is done.
27 grandpa()  
Nested function exercises

Topics: Python Lambda