Python # Decorator

Source: Internet
Author: User

###

Now that I have a simple myfunc function, now I want to add functionality to the MyFunc function. Below we add a Deco feature.

Import TimedefDeco (func): StartTime=time.time () func () EndTime=time.time () msecs= (EndTime-startTime)Print("-->elapsed Time%s s"%msecs)defmyfunc ():Print('Start MyFunc') Time.sleep (3)    Print('End MyFunc') Deco (MyFunc)

However, there is a problem with this approach, which modifies the original invocation method of MyFunc: MyFunc ()------> becomes deco (myfunc). So we made the following changes.

###

def Deco (func):     def wrapper ():         = Time.time ()        func ()        = time.time ()        = (EndTime- startTime)          Print("-->elapsed time%s s"%msecs)    return Wrapper                            # # #返回的是 <function deco.<locals>.wrapper at 0x03234468> can be called via wrapper ()
Def myfunc ():
Print (' Start myfunc ')
Time.sleep (3)
Print (' End MyFunc ')

Print ("MyFunc is%s"%myfunc.__name__)
Myfunc=deco (MyFunc)
Print ("MyFunc is%s"%myfunc.__name__)
MyFunc ()

Output Result:

MyFunc is MyFunc
MyFunc is wrapper
Start MyFunc
End MyFunc
-->elapsed Time 3.0007433891296387 S

After the above changes, a more complete adorner (DECO) is implemented, the adorner has no effect on the original function, and the code of the function call.

The notable thing in the example is that Python is all objects and functions, so the code changes the function object corresponding to "MyFunc".

###

defDeco (func):defwrapper (): StartTime=time.time () func () EndTime=time.time () msecs= (EndTime-startTime)Print("-->elapsed Time%s s"%msecs)returnWrapper@decodefmyfunc ():Print('Start MyFunc') Time.sleep (3)    Print('End MyFunc') MyFunc ()

###

Python # Decorator

Related Article

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.