Python Decorator Decorator

Source: Internet
Author: User

Problem:

    • Defines a new function
    • Want to dynamically add functionality at run time
    • And don't want to change the code of the function itself

Returns a new function through a high-stage function

defF1 (x):returnX*2defNEW_FN (f):#Adorner Functions    deffn (x):Print('Pager'A.__name__+'()')        returnf (x)returnfn#Method 1G1 =new_fn (F1)Print(G1 (5))#Method 2F1 = NEW_FN (F1)#F1 's original definition function was completely hidden.Print(F1 (5))#Output:#Call F1 ()#Ten

Decorative Device

Python's built-in @ syntax is designed to simplify adorners

Similar to the above Method 2

The role of adorners

Can greatly simplify the code and avoid writing repetitive code for each function

    • Print log: @log
    • Detection performance: @performance
    • Database transactions: @transaction
    • URL routing: @post ('/register ')

Python Decorator 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.