A preliminary study on python decorators (recommended)

Source: Internet
Author: User
The following small series will bring you a python ornament (recommended ). I think this is quite good. now I will share it with you and give you a reference. Let's take a look at it with Xiaobian. 1. contains a decorator

# Encoding: UTF-8 ############ contains a decorator ######### def outer (func ): def inner (* args, ** kwargs): # to decorate f1 (), use these two parameters to accept any parameter, no matter how many parameters print "1" r = func (* args, ** kwargs) are defined in f1 # func is used here, do not use f1 print "2" return r return inner @ outer # Here outer should not be enclosed in parentheses def f1 (a1, a2 ): print "a1 + a2 =" return a1 + a2f1 (1, 2)

2. there are two (multiple) decorators

########### Contains two decorators ########## def outer0 (func ): # First def inner (* args, ** kwargs): print "AAAAAAAAA" r = func (* args, ** kwargs) print "BBBBBBBB" return r return innerdef outer (func): # Second def inner (* args, ** kwargs): # f1 () to be decorated (), these two parameters are used here. you can accept any parameter. no matter how many print "1" r = func (* args, ** kwargs) parameters are defined in f1, func is used here, do not use the f1 print "2" return r return inner @ outer0 # decorator. The process is: when f1 () is executed, outer0.inner () and outer0.inner () are first executed (). func calls the inner function of outer, that is, outer. the inner () function is used as the parameter of outer0, # then outer. inner (). func then calls f1 () @ outer # Here outer should not enclose def f1 (a1, a2): print "a1 + a2 = % d" % (a1 + a2) return 1f1 (1, 2)

The above discussion on the python decorator (recommended) is all the content that I have shared with you. I hope you can give me a reference and support me a lot.

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.