Example of a simple adorner:
def servlet(func): print("into servlet")#1 print(servlet)#2 def foo(): print("into foo")#7 print(func)#8,真正的bar函数 func()#9 print("out foo")#13 print(foo)#3 print("out servlet")#4 return foo@servletdef bar(): print("in old bar")/#0 print(bar)#11 print("out old bar")#12print(bar)#5,已经被装饰器装饰了bar()#6
Execution sequence as above, execution result is as follows
into servlet<function servlet at 0x00000186A1341E18><function servlet.<locals>.foo at 0x00000186A1801E18>out servlet<function servlet.<locals>.foo at 0x00000186A1801E18>into foo<function bar at 0x00000186A1801AE8>in old bar<function servlet.<locals>.foo at 0x00000186A1801E18>out old barout fooProcess finished with exit code 0
Examples of variable-parameter adorners:
def desc(func): print("in desc") print(desc) def foo(*arg1,**arg2): print("in foo") print(func) x = func(*arg1,**arg2) print("out foo") return x print(foo) print("out desc") return foo@descdef setArg1(x,y): print("in setArg1") print(setArg1) print("out setArg1") return x + y@descdef setArg2(x,y,z): print("in setArg2") print(setArg2) print("out setArg2") return x + y + zprint(setArg1)print(setArg2)x = setArg1(100,200)y = setArg2(100,200,300)print(x)print(y)
Code as above, execution results are as follows
in desc<function desc at 0x0000024DF2611E18><function desc.<locals>.foo at 0x0000024DF2AD1E18>out descin desc<function desc at 0x0000024DF2611E18><function desc.<locals>.foo at 0x0000024DF2AD1EA0>out desc<function desc.<locals>.foo at 0x0000024DF2AD1E18><function desc.<locals>.foo at 0x0000024DF2AD1EA0>in foo<function setArg1 at 0x0000024DF2AD1AE8>in setArg1<function desc.<locals>.foo at 0x0000024DF2AD1E18>out setArg1out fooin foo<function setArg2 at 0x0000024DF2AD1A60>in setArg2<function desc.<locals>.foo at 0x0000024DF2AD1EA0>out setArg2out foo300600Process finished with exit code 0
Python Decorator Simple Example