# Decorator exercise """ requirement 1、 The function function implements the addition of two integer elements , also sleep 2 second 2、 Print function execution time through decorator 3、 The decorator determines whether to record logs according to parameters """ """ analysis 1、 The first two requirements have been fulfilled before , Don't say it again . 2、 The third requirement requires us to pass a flag bit flag, Essence of decorator @Bar be equal to foo=Bar(foo), There is no place to pass parameters . And because of the open and closed principle , Nor can we modify function functions . So we need to nest another layer of functions , To receive the pass parameters , Then return the function Bar, In effect @Bar Plus transfer parameters """ import time def logger(flag): def bar(foo): def inter(a, b): start_time = time.time() foo(a, b) end_time = time.time() print(' execution time {}'.format(end_time - start_time)) if flag == 'Y': print(' Log ') return inter return bar @logger('Y') # Because of the function logger The return value of Bar, In fact, it is to execute the function first logger( because logger There's... In the back ‘()’ Of , Is to call this function ), Set up flag = ‘y’, And then execute @Bar def foo(a, b): time.sleep(2) print(a + b) foo(3, 4)