Python Adorner method

Source: Internet
Author: User

A few days ago to several new colleagues introduced the project, was asked about the implementation of @login_required, I said this is the Django framework provided by the adorner method, to verify that the user is logged in, as long as the use of the line, because they are not familiar, and did not do too much explanation.

Today, when we look at the Django official website, I suddenly find that the adorner usage is not provided by the Django framework, but rather a syntax of Python, a real sweat, and a well-thought-out python.

At the weekend, sit back and learn about Python's decorator approach.

When it comes to the decorator in the code, it's natural to think of the decorator pattern in the design pattern, in order to prevent re-pigtailed, deliberately flipping through the design pattern of the book, to determine the Python adorner syntax is similar to the function of the adorner mode to implement.

As for the Python decorator syntax, the simple way to do this is to wrap the method foo in a piece of code, add some logic after calling the Foo method, and assign the new method to Foo.

You can also write an encapsulation method in the logic of the wrapper, pass in the parameters, and do some operations. Note that when you have multiple adorner methods to package Foo, it should be wrapped in the order from bottom to top.

defBefore (pre="'):    defDec (f):defwrapper ():PrintPre +"before function"f ()returnwrapperreturnDecdefMiddle (f):defwrapper (): F ()Print "Middle Function"    returnwrapperdefAfter (f):defwrapper (): F ()Print "After function"    returnwrapperdefNextbefore (f):defwrapper ():Print "Nextbefore function"f ()returnWrapper@middle@after@nextbefore@before ("Hello")defTest ():Print "I ' m tester"if __name__=='__main__': Test ()

Printed results:

>>> nextbefore Functionhello before Functioni'm testerafterFunctionmiddle function

Python Adorner method

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.