defdecorator(func): count = 0 defwrapper(): nonlocal count count += 1 result = func() print('{}函数共调用了:'.format(func),count,'次') return result return wrapper
@decoratordef cal(): return10
>>>for i inrange(10): cal() <function cal at 0x00000237C30E7168>函数共调用了:1 次<function cal at 0x00000237C30E7168>函数共调用了:2 次<function cal at 0x00000237C30E7168>函数共调用了:3 次<function cal at 0x00000237C30E7168>函数共调用了:4 次<function cal at 0x00000237C30E7168>函数共调用了:5 次<function cal at 0x00000237C30E7168>函数共调用了:6 次<function cal at 0x00000237C30E7168>函数共调用了:7 次<function cal at 0x00000237C30E7168>函数共调用了:8 次<function cal at 0x00000237C30E7168>函数共调用了:9 次<function cal at 0x00000237C30E7168>函数共调用了:10 次
@decoratordef cal_2(): return100
>>>for i inrange(10): cal_2() <function cal_2 at 0x00000237C30C0798>函数共调用了:1 次<function cal_2 at 0x00000237C30C0798>函数共调用了:2 次<function cal_2 at 0x00000237C30C0798>函数共调用了:3 次<function cal_2 at 0x00000237C30C0798>函数共调用了:4 次<function cal_2 at 0x00000237C30C0798>函数共调用了:5 次<function cal_2 at 0x00000237C30C0798>函数共调用了:6 次<function cal_2 at 0x00000237C30C0798>函数共调用了:7 次<function cal_2 at 0x00000237C30C0798>函数共调用了:8 次<function cal_2 at 0x00000237C30C0798>函数共调用了:9 次<function cal_2 at 0x00000237C30C0798>函数共调用了:10次