[Timlinux] Python Decorator

Source: Internet
Author: User

1. Decorative Device
    1. A syntax format that is used to replace another coding style, a syntactic sugar that clearly identifies such a grammar through a grammatical structure.
    2. Automatically executes code at the end of a decorated object (code that needs to be explicitly stated when not using adorner syntax)
    3. A decorated object can be a function, a class, a decorated object as a function (the adorner is defined as a function adorner), a decorated object is a class (then the adorner is defined as a class adorner)
    4. The adorner itself can be a function, a class.
2. function Adorner function adorner automatically added code:
+----------------------------+----------------------------+| @decorator                 def func ():                def func ():                |     ....                   ||     ....                   | Func = Decorator (func)     |+----------------------------+----------------------------+| func ()                     | decorator ( Func) ()          |+----------------------------+----------------------------+
2.1. The adorner implements the 2.1.1. function Mode implementation
def Decorator (F):     def Tmp_f (*args_for_f):        Inside this function you can add any code you want to execute.        F (*args_for_f)      return tmp_f  #  This returns the function address
2.1.2. Class Mode implementation
class Decorator:     def __init__ (self, F): Self        . __func = F    def__call__(self, *args_for_f): Self        . __func (*args_for_f)* Note: In this way, the decorated object if it is a function in the class, it does not work properly, the meaning of self has changed.
3. class Decorator class adorner automatically added code:
+----------------------------+----------------------------+| @decorator                 class C:                   class C:                   |     ....                   ||     ....                   | c = Decorator (c)           |+----------------------------+----------------------------+| C ()                        | Decorator (c) ()             |+----------------------------+----------------------------+
3.1. The adorner implements the 3.1.1. function Mode implementation
defDecorator (CLS):classTmp_c:def __init__(Self, *args):#CLS (*args)--walking is the process of creating objects that are decorated classes, and then putting the returned object              #stored in a static property of the adorner class instance object. Self.__instance= CLS (*args)#The final access is the instance returned by the adorner class, and the property of the instance is the property of the decorated class instance.        #the same. The implementation method is the delivery of the property.         def __getattr__(self, name):returnGetAttr (self.__instance, name)returnTmp_c@decoratorclass Persondef __init__(self, Name, sex): Self.name=name Self.sex=Sex# Auto-Add code at end: Person =Decorator (person) x= Person ('Tim','Male') # x = Person ('Tim','Male')---> Person has
# equivalent to Tmp_c, call is Tmp_c.__init__Print(x.name) # called the GetAttr (Person object, name), which is returned:'Tim'
3.1.2. Class Mode implementation

There are drawbacks to various implementations, and we recommend the use of functional methods. The main feature of class mode is to consider that __init__ will be called by decorator (), object invocation, obj (), and the Decorator.__call__ method will be called.

4. Decorator Nesting
+-------------------------+-------------------------+| @A                      | |                         | @B                      |                         | | @c                      | fc = C (My_func)         def my_func (..):        | fb = B (FC)              | |    ...                  | FA = A (FB)              |+-------------------------+-------------------------+| @A                      | | |                         @B                      | | |                         @c                      | cc = C (MyClass)         class MyClass:          | bc = B (cc)              | |    ...                  | AC = A (BC)              |+-------------------------+-------------------------+
5.  Adorner parameters
 +----------------------------+----------------------------+| @decorator (A, B) | def  func (): | |     def  func (): |     ....                   || ....                   |                            F1 = Decorator (A, b) | | | Func = F1 (func) |+----------------------------+----------------------------+| Func () | Decorator (A, B) (func) () |+----------------------------+----------------------------+ def   decorator (A, b):  def   F1 (func):  def  F2 (*args_for_func): ...  return   F2  return  F1 
6. Summarize the core of the adorner: through the grammatical structure, hidden behind the decorated function, you need to insert a fixed code method.
    1. Adorner with no parameters: object with the same name as the Decorated object = adorner (Decorated object), run-time order: Execute decorator inside function--decorated function
    2. Adorner with parameters:
      • Object with the same name as a decorated object = (Adorner (adorner parameter)) (Decorated object)
      • = = equivalent to = =
      • Temporary object = Adorner (adorner parameter) # executes the adorner function, returning the intermediate function
      • Object with the same name as a decorated object = temporary object (adorned object) # executes functions inside the adorner and returns the lowest-level wrapper function
    3. Nested adorners:
      • Object with the same name as a decorated object = (outermost adorner (middle adorner ...) (Most inner decorator (decorated object)))
      • = = equivalent to = =
      • After the inner decoration temporary object = The most inner adorner (adorned object) # executes the adorner function and returns the encapsulated function
      • Intermediate trim after temporary object = Intermediate adorner (the most interior post-decoration temporary object) # executes the adorner function and returns the encapsulated function
      • Object with the same name as the decorated object = outermost adorner (intermediate post-decoration temporary object) # executes the adorner function and returns the encapsulated function
      • Run-time order: Top-level, middle-layer, inner-most decorative functions

[Timlinux] Python Decorator

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.