Usage scenarios:
Think of the question: How can you add new functionality to the original module for a production system, with minimal modifications? This can be accomplished with the adorner.
The adorner has two standards:
1, do not modify the original code and the original call mode;
2, can add new functions;
For example, we have a method func1, in which we print two messages and sleep for 1 seconds.
Def func1 (): Print ("This was inthe func1 Methord") Time.sleep (1) Print ("exec the func1 finished")
' Call method ' if __name__ = = "__main__": Func1 ()
|
Now I want to not modify the Func1 () method and how to invoke the premise, add a print the current time of the function, how to implement it?
Import time
def Timmer (func):#Defining adornersTimmer def decotator (*args,**kwargs):#Defining higher order functions PrintDecorator,and Current time is%s ", Args,kwargs)#The method added Func (*args,**kwargs)#To execute a method of passing a variable Return Decotator#It returns the higher-order function address
@timmer#Indicates that the adorner isTimmer, equivalent toFunc1=timmer (FUNC1) Def func1 (): Print"This was in the Func1 Methord") Time.sleep (1) print ("exec the func1 finished")
@timmer def FUNC2 (name): print ("Func2 Methord,and The name is:%s"%name) Time.sleep (1) print ("exec the Func2 finished")
# Call the func1 method Func1 () |
Learn to organize--python decorators