I have learned about decorators before, but I only scratched the surface, and I was confused about how to call them. I just wanted to optimize my current project, so I thought of using decorators, so I studied them in depth.
Let’s take a look at the code first:
import time# 将函数作为参数传入到此方法....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 ") # 表示执行foo函数....
My doubt is that return is obviously a function name. Logically speaking, What is returned is a function address! Is there something wrong with my understanding? Then I checked the information on the Internet, and it was closure again.... But I personally didn't like it. Then I analyzed it myself and summarized a program. After reading it, you will know the reason.
Program:
# coding=utf-8# 带参数的函数 返回一个函数地址就行....def funX(x): def funY(): return x return funY# 不带参数的函数....def funX1(): print("调用函数funX1") def funY1(): print("调用函数funY1") return funY1if __name__ == '__main__': # print(funX(5)()) # 调用有参数的嵌套函数... print(funX1()()) # 调用无参数的嵌套函数...
Isn’t this unlike our decorator? This is our decorator! Therefore, we can understand it according to the above program, that is to say, it first determines the number of parameters and then passes them in separately. Next, let’s rewrite the code:
# coding=utf-8import time# 将函数作为参数传入到此方法....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')
The above is the detailed content of python decorator. For more information, please follow other related articles on the PHP Chinese website!