Python self-study-decorator and python
I have learned some object-oriented knowledge before, And I feel there is a correlation between them. For example, the first element of the decorator is the closeness of the decorated function and cannot be changed; the second is the extensibility of the ornament-based oj.
Main points of the decorator: higher-order functions + nested functions = decorator
Knowledge points to be mastered: 1. functions are variables.
2. High-order functions (function parameters are also functions)
3. nested Functions
Decorator 1: The decorator does not contain parameters, and the decorated functions do not contain parameters.
Simple requirement: There are two simple functions that print content. Now we need to count the running time of each function without changing the source code of the two functions.
Import time
Def timer (func): # Use high-level functions
Def deco (): # use function nesting
Start_time = time. time ()
Func ()
Stop_time = time. time ()
Print ("the func run % s" % (stop_time-start_time ))
Return deco
@ Timer
Def test1 ():
Time. sleep (3)
Print ("I am test1 ")
@ Timer
Def test2 ():
Time. sleep (3)
Print ("I am test2 ")
Test1 ()
Test2 ()
Execution sequence: first, the program goes up and down. When it goes to the defined timer function, it will jump to @ timer and detect that timer is used as the decorator, the system will search for the locations where timer is used as the decorator. After the search is complete, run timer. Then run test1 (), which we call, because test1 is decorated by timer, therefore, the decorator will be executed first. When func () is executed inside the decorator, func () is test1 ()! The same is true for test2 ().
The effect of the modifier is that the source code and function call method of the original function are not changed, and new functions are added to the function.
Decorator 2: parameters included in the decorated Function
Decoration 3: The decoration function returns a value.
Decoration Device 4: The decoration device contains parameters.