A: Decorative essence is a function, function is to add additional functions for other functions
II: Principle:
1) Do not modify the source code of the modified function
2) Do not modify the calling method of the modified function
Three: the implementation of the adorner
1) Adorner = higher order function + function nesting + closure
Example: Add the following function to the function of an execution time
Import Timedef cal (L): res=0 for i in L: res+=i return resret=cal (range) print (ret)
In order to ensure the principle of the adorner, we need to write another function of execution time
Add adorners to functions to print out run-time function def timer (func): def wapper (*args,*kwargs): starttime = time.time () res = func (* Args,**kwargs) stoptime = Time.time () print ("Function run time:%s"% (stoptime-starttime)) return Res Return Wapper
Adorner usage: Declare it in the first function to @timer
@timerdef cal (L): res=0 for i in L: res+=i return resret=cal (range) print (ret)
Python's Decorator