Python Basic Learning----Decorator

Source: Internet
Author: User

The decorator can add some extra functions before and after the target function execution without modifying the target function code.

For example, there is a simple function

Import time
Def func1 ():
Print ("This is a simple function")
Time.sleep (2)

To add a calculation time function to this function, you can use the decorator

Let the function use a decorator, that is, add the @ function name above the definition of the function, as below, which is equivalent to writing func1=outer (FUNC1) to the program behind it

The reason why a parameter outside the function is used in a function is a closed packet

Import time
def outer (f): def inner (): start = Time.time () f () end = Time.time () print (End-start) return Inner@outer#func1=outer (FUNC1) def func1 (): print ("This is a simple function") Time.sleep (2) func1 ()
#输出
This is a simple function.

2.000551223754883

If a function with parameters needs to be modified,

def outer (f):    def inner (x, y):        start = Time.time ()        f (x, y)        end = Time.time ()        print (End-start)    Return Inner@outer#func1=outer (FUNC1) def add (x, y):    print (x+y)    Time.sleep (2) Add

If you want to add some other statements in the decorator, such as a judgment statement, to control whether certain features are used

Import timedef judge (Flag=true):    def outer (f):        def inner (x, y):            start = Time.time ()            f (x, y)            end = Time.time ()            print (End-start)        return inner    if flag==true:        print ("This is a feature")    return Outer@judge () #judge () is actually equivalent to outer, except that you can add the parameter def add (x, y):    print (x+y)    Time.sleep (2) Add

  

Python Basic Learning----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.