python decorator

大家讲道理
Release: 2017-08-19 14:47:35
Original
2209 people have browsed it

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函数....
Copy after login


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()())  # 调用无参数的嵌套函数...
Copy after login


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')
Copy after login


The above is the detailed content of python decorator. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template