- # pcj
- # 定义: 本质是函数 (装饰其他函数) 就是为其他函数增加一些附加功能.
- # 高阶函数 + 嵌套函数 = 装饰器
- # 原则: 1. 不能修改被装饰的函数.
- # 2, 不能修改被装饰的函数的调用方式.
- import time
- def bar(): #bar 为原代码
- time.sleep(3)
- print("in the bar")
- def timer(func):
- def doce():
- start_time=time.time()
- func()
- stop_time=time.time()
- print("the func run time>>:%s:"%(stop_time-start_time))
- return doce
- bar=timer(bar)
- bar()
- # 把 bar 传到另外函数里去
- # 原来 bar 功能只是打印 in the bar 现在增加了打印一个运行时间的功能
来源: http://www.bubuko.com/infodetail-3086337.html