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