Decorators (1)
- Introduced
- HelloWorld
- Demand
- Using functional programming
- Add decorator
- Analytical
Introduced
- The python decorator is called
Decorator
, which is to decorate a module.
- Action: Adds additional functionality to an existing object.
- Similar to annotations in Java, this method is decorated with @xxx in front of the method.
- Unlike annotations in Java, Python's adorners are fairly straightforward.
- Function-Type programming
- Slicing-oriented programming
HelloWorld demand
def Fun (i): Print I
This is a simple method, and now we are going to execute some other code before and after executing this method, such as calculating the run time.
The Simple Way is:
Import Time def Fun (i): = time.time () print i = Time.time ()-T # calculate run time Print ' Run Time: ', str (t) # print Time
This method is inconvenient and cannot be reused.
Using functional programming
Import Time#Calculate run TimedefExec_time (FN, i):#fn: method; I: Parameters of the methodt =time.time () fn (i)#call FNt = time.time ()-T#Calculate run Time Print 'Run Time:', str (t)#Print TimedefFun (i):PrintI#calledExec_time (fun, i)
In this way, in the actual invocation, it is necessary to wrap a layer exec_time
of method, although it can be reused, but it is not flexible.
Add decorator
Now we're going to add modifiers.
fromFunctoolsImportWraps#introduce the package required by the adornerImport Time#define an adornerdefExec_time (FN):#parameter fn: The method to be modified is our fun@wraps (FN)def_ (i):#modification Method, parameter I is fun to pass over the parameterst =time.time () fn (i)#Execution Methodt = time.time ()-TPrint 'Run Time:', str (t)return_#returns the post-decoration method
This completes an adorner that calculates the run time.
@exec_time def Fun (i): Print I@exec_time def fun2 (i): Print ' fun2 ', I
It is very convenient to use.
Analytical
@exec_time
after the method is added fun
, the equivalent method is called automatically when the call is made exec_time(fun)
.
fun
The method is exec_time
decorated, the method is timed at the beginning and end, and the print takes time, which is a cross section, which is the way of programming 面向切面的编程
. The horizontal insertion of logic during method execution can reduce duplication of code in many places.
This site article is for baby bus SD. Team Original, reproduced must be clearly noted: (the author's official website: Baby bus )
Reprinted from "Baby bus Superdo Team" original link: http://www.cnblogs.com/superdo/p/4829345.html
[Python Advanced]002. Decorator (1)