defdecorator(func):defwrapper(*args,**kwargs):print(f'{func.__name__} is running')result=func(*args,**kwargs)returnresultreturnwrapper
增加自己的功能。
Python
1 2 3 4 5 6 7 8 91011
importtimedefdecorator(func):defwrapper(*args,**kwargs):start=time.time()result=func(*args,**kwargs)end=time.time()print(f'Function {func.__name__} took {end-start} seconds')returnresultreturnwrapper
复杂一点的功能。
Python
1 2 3 4 5 6 7 8 9101112131415161718
importtimedefdecorator(func):defwrapper(*args,**kwargs):start=time.time()result=func(*args,**kwargs)end=time.time()print(f'Function {func.__name__} took {end-start} seconds')returnresultreturnwrapperdefsquare(x):returnx*xdecorate_square=decorator(square)print(decorate_square(10))
使用装饰器。
Python
1 2 3 4 5 6 7 8 9101112131415161718
importtimedefdecorator(func):defwrapper(*args,**kwargs):start=time.time()result=func(*args,**kwargs)end=time.time()print(f'Function {func.__name__} took {end-start} seconds')returnresultreturnwrapper@decoratordefsquare(x):returnx*xprint(square(10))
等价的。
Python
1 2 3 4 5 6 7 8 91011121314151617181920
importtimedeftimer(threshold):defdecorator(func):defwrapper(*args,**kwargs):start_time=time.time()result=func(*args,**kwargs)end_time=time.time()print(f'Function {func.__name__} took {end_time-start_time} seconds')if(end_time-start_time>threshold):print(f'Function {func.__name__} took more than {threshold} seconds')returnresultreturnwrapperreturndecorator@timer(0.2)defsleep_04():time.sleep(0.4)sleep_04()
高级用法,装饰器生成器,根据传入的参数来生成装饰器。
Python
1 2 3 4 5 6 7 8 910111213141516171819202122
importtimeimportfunctoolsdeftimer(threshold):defdecorator(func):@functools.wraps(func)defwrapper(*args,**kwargs):start_time=time.time()result=func(*args,**kwargs)end_time=time.time()print(f'Function {func.__name__} took {end_time-start_time} seconds')if(end_time-start_time>threshold):print(f'Function {func.__name__} took more than {threshold} seconds')returnresultreturnwrapperreturndecorator@timer(0.2)defsleep_04():time.sleep(0.4)sleep_04()