1, the role of the adorner
The role of adorners is to add additional functionality to objects that already exist. Adorners are used to decorate functions or classes, using adorners to add actions before and after a function is executed
For example, first define a function that doesn't work, just print out a string
1 def foo (): 2 Print (' hello ') 3 4 foo () #输出你好
Now let's enrich the functionality of this function
1 deffoo1 ():2Before=input ("Enter the person you want to greet:")3In_str="Hello"4 Print("{0},{1}". Format (BEFORE,IN_STR))5after ="Goodbye"6 Print("{0},{1}". Format (before,after))7 8Foo1 () #输出: xx Hello, xx goodbye
Because the programming language follows the principle of open and closed, if the first function is already written in the company's underlying code, then do not allow the random changes, then we can not change the original underlying code, then like the 2nd function, the original underlying function is arbitrarily modified, the general company will not do so, Then you can use the adorner to add some new functionality to the original function, the following FOO2 () function implements the same function as the foo1 () function, and does not modify the original underlying code
1 defFoo2 (func):#Here you can pass the original Foo function as a parameter2 3 deffoo1 ():4before = input ("Enter the person you want to greet:")5 6R=func ()7 returnR#returns the contents of the PrintOut in Foo ()8 Print("{0},{1}". Format (before, R))9 Tenafter ="Goodbye" One Print("{0},{1}". Format (before, after)) A - returnFoo1#returns the contents of the FOO1 function - theFoo2 (foo)
python--Decorator