Home >Backend Development >Python Tutorial >An in-depth explanation of python decorators
This article is mainly about learning the relevant information of Python decorators in a simple and easy-to-understand way. It has a certain reference value. Interested friends can refer to it.
I learned about decorators before, but... I don't know much about it, and I'm confused about its calling method. I just want to optimize the current project, so I thought of using decorators, so I studied the decorators 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 @timeif def foo(arg): print("in foo() %s" % (arg)) if __name__ == '__main__': foo(" Hello ") # 表示执行foo函数....
My doubt is that what is returned 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 funY1 if __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, which means that it first determines the number of parameters and then passes them in separately. Next, let’s rewrite the code:
##
# coding=utf-8 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 # @timeif def foo(arg): print("in foo() %s" % (arg)) if __name__ == '__main__': timeif(foo)(' Hello')
The above is the detailed content of An in-depth explanation of python decorators. For more information, please follow other related articles on the PHP Chinese website!