Knowledge Content:
1. Decorator Introduction
2. Open Closure principle
3. Fixed structure of the adorner
4. Decorative Adorner with parameters
5. Multiple adorners decorate a function
First, the introduction of the decorative device
1. Definition of adorners
Definition: An adorner or a function in essence, but it is intended to decorate other functions, that is, to add some functionality.
2. Function and nature of the adorner
Function: Extend the function of the original function without modifying the original function and its calling mode
Essence: It is a function, it can be said to be a closure function
3. Principles of adorners
(1) cannot modify the source code of the decorated function
(2) cannot modify the calling mode of the decorated function
The above two points plainly, even if the adorner is the function of the decoration is transparent, that is, the function of decoration is not aware of the existence of decorative functions,
The decorated function is the same as the original.
4. A simple decorator
1 #the adorner that counts the run time of the program:2 Import Time3 4 defTimmer (func):5 defWarpper (*args, * *Kwargs):6Start_time =time.time ()7 func ()8Stop_time =time.time ()9 Print("The func run time is%s"% (stop_time-start_time))Ten returnWarpper One A @timmer - deftest1 (): -Time.sleep (3) the Print("In the test1") - - -Test1 ()
5. Knowledge needed to implement adorners
Realize the Knowledge reserve of adorners:
(1) function is "variable"
(2) Higher order functions
(3) Nested functions
High-order functions + nested functions, adorners
For more information on the above can be seen in my other blog, specific location: click here
Ii. the principle of open closure
The open closure principle is an important concept in the development, the main contents are as follows:
- is open to the extension
- The modification is closed.
Of course, the use of adorners in Python development is a good way to implement this principle, because adorners can extend the function of the original function without modifying the original function and its calling method.
Three, the fixed structure of the adorner
Four, with parameters of the adorner
Five or more adorners decorate a function
Python high-order 3 python Adorner