One. Open Closure principle
1. Open for expansion
Any program, it is not possible at the beginning of the design has been thinking of all the features and future do not make any updates and changes. So we have to allow code extensions, add new features.
2. The modification is closed
For example, we write a function, it is likely to have been delivered to other people to use, if we modify it at this time, it is likely to affect other users already using the function.
The adorner perfectly follows the open closure principle.
Two. Useful information for functions
def func (): " " This function is mainly used for drawing and receiving data in real time : return: Returns to the front end of a label ' print(func. __doc__) print(func. __name__) func ()# Result:# This function is mainly used for drawing and receiving data in real time # : Return: Returns to the front of a tag # func
Three. *args,**kwargs
defWrapper (func):defInner (*args,**Kwargs):" "before executing a function" "ret= Func (*args,**Kwargs)" "after the function is executed" " returnretreturnInner@wrapperdefFunc (a,b,c,d):#when receiving a function, add a * aggregation Print(111) func (1,2,3,4)#F1 (*[1,2,3,4]) #执行函数时, add a * scatter
Four. Adorner advanced
1. Decorative Adorner with parameters
Flag =Truedefwrapper_out (flag):defWrapper (func):defInner (*args,**Kwargs):" "before executing a function" " ifFlag:ret= Func (*args,**Kwargs)" "after the function is executed" " Print(222) returnretElse: Ret=func ()returnretreturnInnerreturnwrapper@wrapper_out (flag)#The first step is to call Wrapper_out (flag) and receive the return value wrapperdefFunc ():#The second step is @wrapper, which is Func = wrapper (func) Print(111) func ()#Output Result:#111#222#When flag = False, call inner () to go else#output Result: 111
View Code
2. Multiple adorners decorate a function
defWrapper1 (func):defInner1 (*args,**Kwargs):" "before executing a function" " Print(222) Ret1=func (*args,**Kwargs)" "after the function is executed" " Print(333) returnRet1returnInner1defWrapper2 (func):defInner2 (*args,**Kwargs):" "before executing a function" " Print(555) Ret2= Func (*args,**Kwargs)" "after the function is executed" " Print(666) returnRet2returnInner2@wrapper1@wrapper2deffunc ():Print(111) func ()#run to @wrapper1 and not run at this time, take the next step#when running to @wrapper2, Func = Wrapper2 (func), the resulting func = Wrapper2 (func), the return value is Inner2, which is the func---->inner2#It then runs to @wrapper1, func = Wrapper1 (Inner2), and the return value is Inner1, which is the func----->inner1#then call func (), which calls Inner1 ()##再根据自上而下的运行规律即可以得到结果#Output Result:#222#555#111#666#333
View Code
Python function four (adorner advanced)