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.