装饰器
def logger_decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
line_no = getframeinfo(stack()[1][0]).lineno
info = f'{func.__name__} method. line:{line_no}'
logger.info('Running ' + info)
result = None
try:
result = func(*args, **kwargs)
except Exception as e:
sign = '=' * 60 + '\n'
logger.error(f'{sign}>>>异常时间:\t{datetime.now()}\n>>>异常函数:\t{func.__name__}\n>>>异常:\t{e}')
logger.error(f'{sign}{traceback.format_exc()}{sign}')
logger.info('Finished ' + info)
return result
return wrapper
Refer
import time
import functools
class DelayFunc:
def __init__(self, duration, func):
self.duration = duration
self.func = func
def __call__(self, *args, **kwargs):
print(f'Wait for {self.duration} seconds...')
time.sleep(self.duration)
return self.func(*args, **kwargs)
def eager_call(self, *args, **kwargs):
print('Call without delay')
return self.func(*args, **kwargs)
def delay(duration):
"""装饰器:推迟某个函数的执行。同时提供 .eager_call 方法立即执行
"""
return functools.partial(DelayFunc, duration)
@delay(duration=2)
def add(a, b):
return a + b
add(1, 2)
add.eager_call(1, 2)
|