Decorator2, decorator2
Decorator and Parameters
Import timedef timer (func): # timer (test2) func = test2def deco (): start_time = time. time () func () # run test1 () stop_time = time. time () print ("the action time of the program is {}". format (stop_time-start_time) return deco # returns the deco memory address @ timer # test2 = timer (test2) = decodef test2 (name): time. sleep (2) print ("the name is {}". format (name) test2 ("bigberg") # test2 ("bigberg") = deco ("bigberg") # output Traceback (most recent call last): File "G: /python/untitled/study3/decoration4.py ", line 17, in <module> test2 (" bigberg ") TypeError: deco () takes 0 positional arguments but 1 was given
Therefore, we need to input a parameter in the nested function deco () to ensure that the program is correct.
Import timedef timer (func): def deco (arg1): start_time = time. time () func (arg1) stop_time = time. time () print ("the action time of the program is {}". format (stop_time-start_time) return deco # returns the deco memory address @ timerdef test2 (name): time. sleep (2) print ("the name is {}". format (name) test2 ("bigberg") # output the name is bigbergthe action time of the program is 2.0001132488250732
The parameter has been passed here, but what if the number of parameters is not fixed? We also have non-fixed parameters:
Import timedef timer (func): # timer (test1) func = test1def deco (* args, ** kwargs): start_time = time. time () func (* args, ** kwargs) # run test1 () stop_time = time. time () print ("the action time of the program is {}". format (stop_time-start_time) return deco # returns the deco memory address @ timerdef test1 (): time. sleep (2) print ("in the test1.") @ timerdef test2 (name, age): time. sleep (2) print ("the name is {} and age is {}". format (name, age) test1 () test2 ("bigberg", 18) # output in the test1.the action time of the program is 2.0002853870391846the name is bigberg and age is 18the action time of the program is 2.000582218170166
It can be seen that after non-fixed parameters are used, any parameters of the modified function can run normally.