An adorner (decorator) is an advanced Python syntax. Adorners can be used to process a function, method, or class. In Python, we have several methods for working with functions and classes, such as in Python closures, where we see the function object as the result of a function's return. With respect to other methods, the adorner has a simple syntax and a code with high readability. As a result, adorners are widely used in Python projects.
This is the content that is introduced in the Python Study Group, now learn to sell, more practice is a good way to learn.
The first step: The simplest function, ready to add additional functionality
Step two: Use decorative functions to add additional functionality before and after the function is executed
Step three: Use the syntax sugar @ to decorate the function
Fourth step: Use the inline wrapper function to ensure that each new function is called
Fifth step: Decorate the function with parameters
Sixth step: Decorate the function with indeterminate number of parameters
Seventh step: Let the adorner with parameters
Eighth step: Let the adorner with class parameters
Nineth Step: Adorner with class parameters, and split the public class into other py files, but also demonstrates the application of a function of multiple adorners
#-*-CODING:GBK-*-' mylocker.py: public class for example 9.py ' class Mylocker:def __init__ (self):p rint ("mylocker.__init__ () Called. ") @staticmethoddef acquire ():p rint ("Mylocker.acquire () called.") @staticmethoddef unlock ():p rint ("Mylocker.unlock () called.") Class Lockerex (Mylocker): @staticmethoddef acquire ():p rint ("Lockerex.acquire () called.") @staticmethoddef unlock ():p rint ("Lockerex.unlock () called.") def lockhelper (CLS): ' CLS must implement acquire and release static method ' Def _deco (func):d ef __deco (*args, **kwargs):p rint ("before%s Called. "% func.__name__) Cls.acquire () Try:return func (*args, **kwargs) Finally:cls.unlock () return __decoreturn _deco # -*-CODING:GBK-*-
"' Example 9: Adorner with class parameter and split public class into other py files
It also demonstrates the application of multiple adorners to a function
The above for you to share the Python decorator Introductory Learning tutorial (nine-step study), I hope to be helpful to everyone.