A simple decorative device
1. Why use adorners?
The function of the adorner: the function of the original function is extended without modifying the original function and its calling mode
The essence of adorners: a closure function
So let's take a look at a simple decorator: the ability to calculate the execution time of each function
1 Import Time2 defWrapper (func):3 definner ():4start=time.time ()5 func ()6End=time.time ()7 Print(end-start)8 returnInner9 Ten defhahaha (): OneTime.sleep (1) A Print('AAAAA') -Hahaha=Wrapper (hahaha) -Hahaha ()a simple decorator
The above function is somewhat not brief, imperfect, the following introduced the grammar sugar.
1 Import Time2 defWrapper (func):3 definner ():4start=time.time ()5 func ()6End=time.time ()7 Print(end-start)8 returnInner9 @wrapperTen defKKK ():#equivalent to Kkk=wrapper (KKK) One Print('AAAAA') AKKK ()decorator-------Grammar sugar
The above adorner is a function without parameters, now decorate a parameter with what to do?
1 Import Time2 defTimmer (func):3 defInner (a):4start=time.time ()5 func (a)6End=time.time ()7 Print(end-start)8 returnInner9 Ten @timmer One defhahaha (a): ATime.sleep (1) - Print(a) - the -Hahaha (5)
adorner with one parameter
1 Import Time2 defTimer (func):3 defInner (*args,**Kwargs):4Start =time.time ()5Re = func (*args,**Kwargs)6End=time.time ()7 Print(end-start)8 returnRe9 returnInnerTen One@timer#==> func1 = Timer (func1) A defFunc1 (A, b): - Print('In func1') - Print(A, b) the -@timer#==> func1 = Timer (func1) - defFunc2 (a): - Print('In Func2 and get a:%s'%(a)) + return 'fun2 over' - +Func1 () A Print(Func2 ('aaaaaa'))the original function adorner with multiple parameters
1 Import Time2 defTimer (func):3 defInner (*args,**Kwargs):4Start =time.time ()5Re = func (*args,**Kwargs)6End=time.time ()7 Print(End-start)8 returnRe9 returnInnerTen One@timer#==> func1 = Timer (func1) A defJJJ (a): - Print('In jjj and get a:%s'%(a)) - return 'fun2 over' the -JJJ ('aaaaaa') - Print(JJJ ('aaaaaa'))adorner with return value
Ii. the principle of open closure
1. Open for expansion
2. The modification is closed
Three, the fixed structure of the adorner
1 Import Time2 defWrapper (func):#Decorative Device3 defInner (*args, * *Kwargs):4 " "content extension prior to function execution" "5ret = func (*args, * *Kwargs)6 " "content extension prior to function execution" "7 returnret8 returnInner9 Ten@wrapper#=====>aaa=timmer (AAA) One defaaa (): ATime.sleep (1) - Print('FDFGDG') -AAA ()View Code
Python-------Decorator