A Preliminary Study on python decorators and a preliminary study on python decorations

Source: Internet
Author: User

A Preliminary Study on python decorators and a preliminary study on python decorations

1. contains a decorator
1 # encoding: UTF-8 2 3 ############ contains a decorator ######### 4 def outer (func ): 5 def inner (* args, ** kwargs): # To decorate f1 (), use these two parameters to accept any parameter, whether f1 defines several parameters 6 print "1" 7 r = func (* args, ** kwargs) # func is used here, do not use f1 8 print "2" 9 return r10 return inner11 12 @ outer # Here outer do not add brackets 13 def f1 (a1, a2 ): 14 print "a1 + a2 =" 15 return a1 + a216 17 f1 (1, 2)
2. There are two (multiple) decorators
1 ########### contains two decorators ########## 2 3 def outer0 (func ): # First 4 def inner (* args, ** kwargs): 5 print "AAAAAAAAA" 6 r = func (* args, ** kwargs) 7 print "bbbbbbbbbb" 8 return r 9 return inner10 11 def outer (func): # second 12 def inner (* args, ** kwargs): # f1 () to be decorated (), these two parameters are used here. You can accept any parameter. No matter how many parameters are defined in f1, 13 print "1" 14 r = func (* args, ** kwargs) # func is used here, do not use the f115 print "2" 16 return r17 return inner18 @ outer0 # decorator. The process is: when f1 () is executed, outer0.inner () and outer0.inner () are executed first (). func calls the inner function of outer, that is, outer. inner () function as the parameter of outer0, 19 # Then outer. inner (). func then calls f1 () 20 @ outer # Here outer should not be enclosed in brackets 21 def f1 (a1, a2): 22 print "a1 + a2 = % d" % (a1 + a2) 23 return 124 25 f1)View Code
 

 

 

 

 

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.