Before I learned a bit about object-oriented knowledge, I felt that there was a correlation, for example, the first element of the adorner was the closure of the decorated function, not the change, and the second was the extensibility of the OJ body of the adorner.
Adorner essentials: higher-order functions + nested functions = adorners
Knowledge points to be mastered: 1, function as variable
2. Higher-order functions (function parameters are also functions)
3. Nested functions
Adorner one: The adorner does not have parameters, the function is decorated without parameters
Simple requirements: Existing two simple print content functions, now need to count each function run time without changing the two function source code
Import time
def timer (func): #用到高阶函数
Def deco (): #用到函数嵌套
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 order: First, the program from the top down, go to the definition of the timer function will jump to @timer place, detected that the timer is used as an adorner, the system will go to search where to use the timer as the adorner, after the completion of the search, the execution of the timer, and then execute the test1 we call (), because test1 is decorated by a timer, so the adorner is executed first, and when it executes to func () inside the adorner, then Func () is test1 ()! Test2 () is the same
The effect of the adorner is: there is no change in the original function of the source code and function call mode, but also to add new functions to the function
Adorner two: decorated function with parameters
Adorner three: The decorated function has a return value
Decorator Four: The adorner itself with parameters
Python self-taught music-an introduction to decorators