Python multi-layer decorator usage instance analysis and python instance analysis

Source: Internet
Author: User

Python multi-layer decorator usage instance analysis and python instance analysis

This example describes how to use a Python multi-layer decorator. We will share this with you for your reference. The details are as follows:

Preface

The Python decorator can supplement the functions of a function without damaging the original structure of the function. When we need to add different functions to a function, we may need to use multi-layer decorators. During my use, I encountered two kinds of decorative devices stacked. Here I will write down these two cases as a pitfall record.

Case 1

def A(funC):  def decorated_C(funE):    def decorated_E_by_CA(*args, **kwargs):      out = funC(funE)(*args, **kwargs)      return out +' > decorated by A'    return decorated_E_by_CA  return decorated_C@Adef C(funE):  def decorated_E_by_C(str):    return funE(str)+' > decorated by C'  return decorated_E_by_C@Cdef E(str):  return strprint E('A string is ')

In this case, firstE(str) = C(E)(str)And thenC = A(C)AndE(str) = A(C)(E)(str). In this way, their relationship is clear. The decorator A is decorated with the decorator C, and it returnsDecoratorAnd the decorator that has been decorated can decorate function E. In the code above, decorated_C is a decoration device that has been decorated.

Case 2

def A(funE_decorated_by_C):  def redecorated_E(str):    return funE_decorated_by_C(str)+' > redecorated by A'  return redecorated_Edef C(funE):  def decorated_E(str):    return funE(str)+' > decorated by C'  return decorated_E@A@Cdef E(str):  return strprint E('A string is ')

In this caseE(str) = A(C(E))(str). First, the C decoration function E is returned, A function decorated by C is returned, and then the C decoration function is decorated by. The difference with the first case is that the decoration device A here is decorated withFunction, AndNot a 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.