python进阶:装饰器

装饰器:

定义:decorator,在代码运行期间为函数动态增加功能

注意:decorator本质上是一个返回函数的高阶函数;decorator总是接收一个函数作为参数,并返回一个函数

举例:

 1 # 获取函数执行时间
 2 
 3 def getcosttime(func):
 4     @functools.wrans(func)
 5     def wrapper(*args,**kwargs):
 6         since = time.time()
 7         res = func(*args,**kwargs)
 8         elapsed = time.time() - since
 9         name = func.__name__
10         print("%s-----%s" %(name,elapsed))
11         return res
12     return wrapper
13 
14 
15 @getcosttime
16 def test1():
17     time.sleep(3)

输出:test2-----3.007......

原文地址:https://www.cnblogs.com/jinziguang/p/14886115.html