python 入坑路--装饰器(语法糖)小高潮

注意咯前戏做足了,下面要进入高潮。

前面试过了只用高阶函数或则嵌套函数都无法现实装饰器的功能,所以需要结合两者才能实现装饰器,级之前装饰器的定义。

 

 1 import time
 2 
 3 def bar():
 4     time.sleep(2)
 5     print("in the bar")
 6 
 7 def timer(func):
 8     def wrapper():
 9         start_t=time.time()
10         func()
11         stop_t=time.time()
12         print("func run time is {}".format(stop_t-start_t))
13     return func   #非常重要,返回的是函数名,即内存地址,不带括号,带括号就是函数执行结果14 
15 bar=timer(bar)  #貌似调用方式还是比较麻烦,
16 bar()
 1 import time
 2 
 3     
 4 def timer(func):
 5     def wrapper():
 6         start_t=time.time()
 7         func()
 8         stop_t=time.time()
 9         print("func run time is {}".format(stop_t-start_t))
10     return func
11 
12 @timer  # python 装饰器的引用固定语法@  即实现了 bar=timer(bar)
13 def bar():
14     time.sleep(2)
15     print("in the bar")
posted @ 2017-12-31 23:24  东郭仔  阅读(106)  评论(0)    收藏  举报