First, the decoration device
Adorner: Essentially a function that adds additional functionality to other functions
The principle of adorners:
- Do not modify the source code of the modified function
- Do not modify how the modified function is called
Knowledge Reserve for Decorators:
Adorner = higher order function + function nesting + closure
Second, higher order function
Definition of higher order functions:
- The receive parameter of a function is a functional name
- The return value of a function is a functional name
- Any one of the above conditions can be a higher-order function
Import Timedeffun1 (): Time.sleep (0.5) Print("Hello")defComputing_run_time (fun):"""calculate function Run time:p Aram fun:: Return:"""start_time=Time.time () fun () End_time=time.time ()Print("Run time%s"% (End_time-start_time)) Computing_run_time (FUN1)"""Advantage: Without modifying the function source code, add additional functional disadvantage to the function: Change the calling mode"""
the receive parameter of the function is the name of the functor
Import Timedeffun1 (): Time.sleep (0.5) Print("Hello")defComputing_run_time (fun):"""calculate function Run time:p Aram fun:: Return:"""Fun ()returnfunfun1=computing_run_time (FUN1) fun1 ()"""Pros: No change to function call method disadvantage: Cannot add new function for function"""
The return value of the function is the name of the functor
Note: Only higher-order functions do not meet the needs of adorners
Three, function nesting and closure
"" "Closure: the first must be an internally defined function that contains a reference definition for an outer scope instead of a global domain name word: The code for the intrinsic function contains a reference to the code of the external function, but must not be a reference to the global scope" "" Def Fun1 (): print ("fun1 ") name = 1 def fun2 (): Print ( " fun2 ") print (name) def fun3 (): Print ( " fun3 ") print (name ) fun3 () fun2 () fun1 ()
Python learning "Fourth" Python Function (ii)