This article is mainly with you to learn about the Python decoration of the relevant information, with a certain reference value, interested in small partners can refer to
Before I learned about the adorner, but it will be a little fur, but also confused about the way they call, just now the project I want to optimize, I think of using the adorner, so in-depth study of the next adorner.
First look at the code:
Import time# passes the function as a parameter to this method .... def timeif (func): def wrapper (ARG): print ("in wrapper ()%s"% (ARG)) start = Time.clock () func (arg) end = Time.clock () print ("used:%s%s"% (End-start, arg)) return Wrapper@timeifdef foo (ARG): print ("in foo ()%s"% (ARG)) if __name__ = = ' __main__ ': foo ("Hello") # means execute foo function ....
My doubts is clearly return is a function name, according to the truth, return is a function address Ah! I understand there's a problem? Later on the Internet to check information, but also closures .... But I personally do not have a cold, and then analysis, summed up a procedure, after reading you know why.
Program:
# coding=utf-8# function with parameters returns a function address on the line .... def funx (x): def funy (): Return x return funy# function without parameters .... def funX1 (): print ("Call function FunX1") def funY1 (): print ("Call function funY1") return funy1if __name__ = = ' __main__ ': # Print (Funx (5) ()) # Call a nested function with parameters ... Print (FunX1 ()) # Call a parameterless nested function ...
It's not like our decorator, is it? This is our decorator! Therefore, we can follow the above procedure to understand, that is, it is the first to determine the number of parameters, followed by the respective incoming, below, we rewrite the code:
# Coding=utf-8import time# passes the function as a parameter to this method .... def timeif (func): def wrapper (ARG): print ("in wrapper ()%s"% (arg ) start = Time.clock () func (arg) end = Time.clock () print ("used:%s%s"% (End-start, arg)) return wrapper# @timeifdef foo (ARG): print ("in foo ()%s"% (ARG)) if __name__ = = ' __main__ ': timeif (foo) (' Hello ')