Python's Decorator

Source: Internet
Author: User

 

A: Decorative essence is a function, function is to add additional functions for other functions

II: Principle:

1) Do not modify the source code of the modified function

2) Do not modify the calling method of the modified function

Three: the implementation of the adorner

1) Adorner = higher order function + function nesting + closure

Example: Add the following function to the function of an execution time

Import Timedef cal (L):    res=0 for    i in L:        res+=i    return resret=cal (range) print (ret)

In order to ensure the principle of the adorner, we need to write another function of execution time

Add adorners to functions to print out run-time function def timer (func):    def wapper (*args,*kwargs):        starttime = time.time ()        res = func (* Args,**kwargs)        stoptime = Time.time ()        print ("Function run time:%s"% (stoptime-starttime))        return  Res    Return Wapper

Adorner usage: Declare it in the first function to @timer

@timerdef cal (L):    res=0 for    i in L:        res+=i    return resret=cal (range) print (ret)

  

 

Python's 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.