Nine-Step learning python Decorator

Source: Internet
Author: User
Tags python decorator
This example describes the Python adorner. Share to everyone for your reference. The specific analysis is as follows:

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

#-*-CODING:GBK-*-"Example 1: The simplest function that represents a call to two" Def MyFunc ():  print ("MyFunc () called.") MyFunc () MyFunc ()

Step two: Use decorative functions to add additional functionality before and after the function is executed

#-*-CODING:GBK-*-"Example 2: Replacement function (decoration) The parameter of the adornment function is the function object that is decorated, returning the substance statement of the original function object adornment: MyFunc = Deco (myfunc)" Def deco (func):  print ("before MyFunc () called.")  Func ()  print ("after MyFunc () called.")  return Funcdef MyFunc ():  print ("MyFunc () called.") MyFunc = Deco (MyFunc) MyFunc () MyFunc ()

Step three: Use the syntax sugar @ to decorate the function

#-*-CODING:GBK-*-"Example 3: Use the syntax sugar @ to decorate the function, equivalent to" MyFunc = Deco (myfunc) "but found that the new function was only called for the first time, and the original function called" Def deco (func) more than once:  Print ("Before MyFunc () called.")  Func ()  print ("after MyFunc () called.")  return Func@decodef MyFunc ():  print ("MyFunc () called.") MyFunc () MyFunc ()

Fourth step: Use the inline wrapper function to ensure that each new function is called

#-*-CODING:GBK-*-"Example 4: Use the inline wrapper function to ensure that each new function is called, the formal parameters and return values of the inline wrapper function are the same as the original function, and the adornment function returns the inline wrapper function object ' Def deco (func):  def _deco ( ):    print ("before MyFunc () called.")    Func ()    print ("after MyFunc () called.")    # You do not need to return func, you should actually return the return value of the original function return  _deco@decodef myfunc ():  print ("MyFunc () called.")  Return ' OK ' MyFunc () MyFunc ()

Fifth step: Decorate the function with parameters

#-*-CODING:GBK-*-"Example 5: Decorate a function with parameters, the formal parameter and return value of the inline wrapper function is the same as the original function, and the adornment function returns the inline wrapper function object ' Def deco (func):  def _deco (A, B):    print ("before MyFunc () called.")    ret = func (A, b)    print ("after MyFunc () called. Result:%s "% ret"    return ret  return _deco@decodef MyFunc (A, b):  print ("MyFunc (%s,%s) called."% (A, b))  Return a + bmyfunc (1, 2) MyFunc (3, 4)

Sixth step: Decorate a function with an indeterminate number of parameters

#-*-CODING:GBK-*-"Example 6: Decorating a function with an indeterminate number of parameters (*args, **kwargs), auto-adaptive variable parameter and named parameter ' Def deco (func):  def _deco (*args, * * Kwargs):    print ("before%s called."% func.__name__)    ret = func (*args, **kwargs)    print ("after%s called. Result:%s "% (func.__name__, ret))    return ret  return _deco@decodef MyFunc (A, b):  print (" MyFunc (%s,%s)  Called. "% (A, b))  return A+b@decodef Myfunc2 (A, B, c):  print (" Myfunc2 (%s,%s,%s) called. "% (A, B, c))  return A+b+cmyfunc (1, 2) MyFunc (3, 4) MYFUNC2 (1, 2, 3) MYFUNC2 (3, 4, 5)

Seventh step: Let the adorner with parameters

#-*-CODING:GBK-*-"Example 7: On the basis of example 4, let the adorner with parameters, and the previous example a layer more than the outer layer of packaging. The decorated function name should actually be more meaningful "Def deco (ARG): Def  _deco (func):    def __deco ():      print (" before%s called [%s]. "% (func.__ NAME__, Arg))      func ()      print ("after%s called [%s]."% (func.__name__, arg))    return __deco  return _ Deco@deco ("MyModule") def myfunc ():  print ("MyFunc () called.") @deco ("Module2") def MYFUNC2 ():  print ("Myfunc2 () called.") MyFunc () Myfunc2 ()

Eighth step: Let the adorner with class parameters

#-*-CODING:GBK-*-"Example 8: Adorner with class parameter ' class Locker:  def __init__ (self):    print (" locker.__init__ () should is not Called. ")  @staticmethod  def acquire ():    print ("Locker.acquire () called. (This is a static method)")  @staticmethod  def release ( ):    Print ("Locker.release () called. (no object instance required)") def deco (CLS): "The  CLS must implement the acquire and release static methods '  def _ Deco (func):    def __deco ():      print ("before%s called [%s]."% (func.__name__, CLS))      Cls.acquire ()      Try:        return func ()      finally:        cls.release ()    return __deco  return _deco@deco (Locker) def MyFunc ():  print ("MyFunc () called.") MyFunc () MyFunc ()

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):    print ("mylocker.__ Init__ () called. ")  @staticmethod  def acquire ():    print ("Mylocker.acquire () called.")  @staticmethod  def unlock ():    print ("Mylocker.unlock () called.") Class Lockerex (Mylocker):  @staticmethod  def acquire ():    print ("Lockerex.acquire () called.")  @staticmethod  def unlock ():    print ("Lockerex.unlock () called.") def lockhelper (CLS):  ' CLS must implement acquire and release static method '  def _deco (func):    def __deco (*args, **kwargs):      print ("before%s called."% func.__name__)      cls.acquire ()      try:        return func (*args, **kwargs)      finally:        cls.unlock ()    return __deco  return _deco

#-*-CODING:GBK-*-"Example 9: Adorner with class parameter, and split public class into other PY files also demonstrates applying multiple adorners to a function" from Mylocker import *class example:  @ Lockhelper (mylocker)  def myfunc (self):    print ("MyFunc () called.")   @lockhelper (Mylocker)  @lockhelper (Lockerex)  def myfunc2 (self, A, b):    print ("Myfunc2 () called.")    Return a + bif __name__== "__main__":  a = example ()  a.myfunc ()  print (A.myfunc ())  print (A.MYFUNC2 (1, 2))  print (A.MYFUNC2 (3, 4))

Hopefully this article will help you with Python programming.

  • 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.