def func(): print("仓鼠") def flower(f): def inner(): print("111") f() print("222") return inner flower(func)() 可以理解为 函数名和()是一个组合 当这个组合为func()时函数被启动,当组合缺少一个时候就会不启动函数, 这时函数名可以传递的特性就体现出来了,我传递函数名,再给函数名赋值比如F=func F() ,这句话的意思就等于了 func()这样我们可以运用这个算法做很多事,比如外部函数调入到内部函数里运行.
https://q1mi.github.io/PythonBlog/post/advanced_decorator/装饰器进阶
import time # def func(): # print('嘻嘻更健康') # import time # start_time = time.time() # time.sleep(0.1) # func() # end_time = time.time() # print('----> 执行效率%s'%(end_time - start_time)) # def timmer(f): # start_time = time.time() # time.sleep(0.1) # f() # end_time = time.time() # print('----> 执行效率%s'%(end_time - start_time)) # func() # f1 = func # func # func = timmer # timmer # func(f1) # def timmer(f): # def inner(): # start_time = time.time() # time.sleep(0.1) # f() # end_time = time.time() # print('----> 执行效率%s' % (end_time - start_time)) # return inner # func = timmer(func) # inner # func() # inner() #简单的装饰器 def func(): print('嘻嘻更健康') def timmer(f): def inner(): start_time = time.time() time.sleep(0.1) f() end_time = time.time() print('----> 执行效率%s' % (end_time - start_time)) return inner func = timmer(func) # inner func() # inner() #语法糖 @ # def timmer(f): # def inner(): # start_time = time.time() # time.sleep(0.1) # f() # end_time = time.time() # print('----> 执行效率%s' % (end_time - start_time)) # return inner # @timmer # func = timmer(func) # def func(): # print('嘻嘻更健康') # func() # inner() # 带参数的装饰器 # def timmer(f): # def inner(*args,**kwargs): # start_time = time.time() # time.sleep(0.1) # f(*args,**kwargs) # end_time = time.time() # print('----> 执行效率%s' % (end_time - start_time)) # return inner # @timmer # func = timmer(func) # def func(a): # print('%s嘻嘻更健康'%a) # @timmer # func1 = timmer(func1) # def func1(a,b): # print('%s和%s嘻嘻更健康' %(a,b)) # func('萌哥') # # func1('萌哥','杀毒软件') # def shouye(): # pass # def riji(): # pass # def wenzhang(): # pass # 带返回值的装饰器 # def timmer(f): # def inner(*args,**kwargs): # start_time = time.time() # time.sleep(0.1) # ret = f(*args,**kwargs) # 222 # end_time = time.time() # print('----> 执行效率%s' % (end_time - start_time)) # return ret # return inner # # @timmer # func = timmer(func) # def func(a): # return 222 # print(func('萌哥')) #通用装饰器 def wrapper(func): def inner(*args,**kwargs): '''执行函数前操作''' ret = func(*args,**kwargs) '''执行函数后的操作''' return ret return inner @wrapper def func(): print(66) func()