Python advanced "Nineth" decorator

Source: Internet
Author: User

What is an adorner?

The adorner itself is a function and adds additional functionality to other functions

The principle of adorners: 1. Do not modify the source code of the Decorated object 2. do not modify the calling method of the decorated object
Adorner = higher order function + function nesting + closure

# Res=timmer (Test) #返回的是wrapper的地址 # res () #执行的是wrapper ()

# Test=timmer (test) #返回的是wrapper的地址 # test () #执行的是wrapper ()

# @timmer is equivalent to Test=timmer (test)

# #搭一个高阶函数与函数嵌套的框架 # def Timmer (func): #     def wrapper (): #         Print (func) #         func () #     return Wrapperimport Timedef Timmer (func):    def wrapper ():        start_time=time.time ()        # Print (func)        Res=func () #由于执行新获得的test , so execute wrapper,func as a local variable, not currently, then go to the previous layer to find, that is, test, run test        stop_time = Time.time ()        print (' Run time is%s '% (Stop_time- start_time))        #wrapper里没有返回值, so no matter how the test is changed, the return value is None return        res# since Func runs the test, the value of Func is assigned to Res, Return res is the return value of test    wrapper@timmer# equivalent to test = Timmer (test) #把test函数作为参数传给timmer, execution Timmer gets the return value wrapper, and assign it to testdef test ():    time.sleep (3)    print (' Test run complete ') return    ' This is the return value of test ' test () #执行新的test, The actual execution is wrapper, which is to not change the way test is called

Python advanced "Nineth" decorator

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.