装饰器基础
def timeit(func):
def __(*args, **kwargs):
t1 = time.time()
ret = func(*args, **kwargs)
t2 = time.time()
print('call the function:%s spend time:%0.2f s' % (func.__name__, int((t2-t1))))
return ret
return __
@timeit
def func():
print('Decorator')
func()
>>> Decorator
>>> call the function:func spend time:0.00 s
带参数的装饰器
def timeit(para1):
def decorator(func):
def __(*args, para1=para1,**kwargs):
print(para1)
t1 = time.time()
ret = func(*args, **kwargs)
t2 = time.time()
print('call the function:%s spend time:%0.2f s' % (func.__name__, int((t2-t1))))
return ret
return __
return decorator
@timeit('Para from decorator')
def func():
print('Decorator')
>>> func()
>>> Para from decorator
>>> Decorator
>>> call the function:func spend time:0.00 s
装饰器参数在原函数中录入
实质是在里层函数新增参数,装饰器返回的是里层函数,
def timeit(para1, para2=None):
def decorator(func):
def __(*args, para1=para1,para2=para2, **kwargs):
print(para1)
print(para2)
t1 = time.time()
ret = func(*args, **kwargs)
t2 = time.time()
print('call the function:%s spend time:%0.2f s' % (func.__name__, int((t2-t1))))
return ret
return __
return decorator
@timeit('Para from decorator')
def func():
print('Decorator')
func(para2='Para2 from func')
>>> Para from decorator
>>> Para2 from func
>>> Decorator
>>> call the function:func spend time:0.00 s