Previously, we wrote an adorner in a decorator for statistical function call consumption time for statistical function call time. The code is as follows:
fromTimeImport Time fromTimeImportSleepdefcount_time ():deftmp (func):defWrapped (*args, * *Kargs): Begin_time=Time () result= Func (*args, * *Kargs) End_time=Time () Cost_time= End_time-Begin_timePrint '%s called Cost time:%s'% (func.__name__, Cost_time)returnresultreturnWrappedreturnTmp
For this adorner, we must use this:
@count_time () def Test (): sleep (0.5)if__name__'__main__' : Test ()
Notice here that the adorner is appended with parentheses.
If we do not add parentheses:
@count_time def Test (): sleep (0.5)if__name__'__main__ ' : Test ()
will produce an error:
Traceback (most recent): " 16.py " in <module> @count_timeTypeError: Count_time () takes no arguments (1 given)
But when a lot of adorners are used, they don't have to be bracketed, so what's going on?
We will rewrite the above adorner:
fromTimeImport Time fromTimeImportSleepImportSYSdefCount_time (func):defWrapped (*args, * *Kargs): Begin_time=Time () result= Func (*args, * *Kargs) End_time=Time () Cost_time= End_time-Begin_timePrint '%s called Cost time:%s Ms'% (func.__name__, float (cost_time) *1000) returnresultreturnWrapped
At this point, there is no need to add parentheses.
The difference between the two is that the first parenthesis, which allows the user to pass in custom information, requires an extra layer of wrapping, which is not required for brackets.
So when we need to customize some of the message in the adorner, we need to use parentheses.
For this statistical time adorner, we can customize the information like this:
#Coding:utf-8 fromTimeImport Time fromTimeImportSleepdefcount_time (msg):deftmp (func):defWrapped (*args, * *Kargs): Begin_time=Time () result= Func (*args, * *Kargs) End_time=Time () Cost_time= End_time-Begin_timePrint 'msg:%s,%s called Cost time:%s'% (msg, func.__name__, Cost_time)returnresultreturnWrappedreturnTmp
Then use this:
@count_time ("foobar")def Test (): sleep (0.5) @count _time (" test message ")def test2 (): Sleep (0.7 if__name__'__main__': Test () test2 ()
The results are as follows:
Msg:foobar, test called cost time:0.5015408992770.701622009277
After synthesizing the previous several, write a complete decorator tutorial.
The difference between parentheses and brackets when using adorners