今天偶遇老男孩教育的python装饰器的讲解视频,才突然意识到装饰器的优点所在,真是一个伟大的发明,既简单又优雅。有了装饰器的存在,可以有效的帮助开发者在日后对系统需求有改动升级在不需要更改原来代码的情况下轻松解决。
""" 装饰器: 定义:本质是函数,(装饰其他函数)就是为其他函数添加附加功能 原则:1.不能修改被装饰的函数的源代码 2.不能修改被装饰的函数的调用方式 """ import time def timmer(func): def warpper(*args,**kwargs): start_time = time.time() print("先执行这里的东西") func() print("然后执行完test1函数,继续执行这里") stop_time = time.time() print("the func run time is %s"%(stop_time-start_time)) return warpper() @timmer def test1(): time.sleep(3) print("in the test1") test1
结果:
先执行这里的东西 in the test1 然后执行完函数,完了后,继续执行这里 the func run time is 3.0011165142059326 Hello world