Use of adorners:
Use when you do not want to modify the function's invocation, but want to add content to the function
Why use adorners: Software entities should be extensible and non-modifiable. In other words, the extension is open, and the modification is closed. Thus, the open closure principle is introduced: open to expansion, meaning that there are new requirements or changes, the existing code can be extended to adapt to the new situation. Enclosing a modification means that once the class is designed, it can do its work independently, rather than making any modifications to the class.so the function should be closed after it has been developed so as to prevent some unnecessary errors from happening.this time I want to add functionality to the original function so long used the adornerThe fixed mode of the adorner
1 2 3 4 5 6 |
# Decorator's Fixed mode def wrapper(func): def Inner(*args, **kwargs): RET = func(*args, **kwargs) return RET return Inner |
Case:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21st 22 23 24 25 26 27 |
#-*-Coding:utf-8-*-
# above for a normal function call # But what if I'm going to print out the function's run time for the function without modifying the contents of the function? This is where the decorator is used. Import Time
defWrapper(Func): defInner(*args,**kwargs): Start_time= Time. Time() Print(' Nihao ') Ret=Func(*args,**kwargs) End_time= Time. Time() Print(End_time-start_time) returnRet returnInner
# define a function Func2 @Wrapper# syntax sugar, do decorate the following function equals call Func2 = Wrapper (FUNC2) defFunc2(A): Print("Hello") returnA +1
Ret=Func2(2)# The Func2 here actually points to the address of inner, the function name is unchanged Print(Ret)
# This succeeds in modifying the function without changing the calling function . |
The essence of the adorner is to call the decorated function in the function nesting to increase the flexibility of the function!
The use of adorners in Python and the fixed mode