函数装饰器的介绍:
https://www.runoob.com/w3cnote/python-func-decorators.html
1,打印函数运行时间,减少重复代码
def logit_time(func):
"""
打印函数运行起始时间、终止时间、运行时间的装饰器
"""
@wraps(func)
def printFuncRunTime(*args, **kwargs):
"""
打印函数运行时间
"""
time1 = datetime.now()
print(time1, f'{func.__name__} start running.')
res = func(*args, **kwargs)
time2 = datetime.now()
print(time2, f'{func.__name__} done.')
print(f'{func.__name__} total use time:', time2 - time1)
return res
return printFuncRunTime
使用装饰器:
@logit_time
def one_car_resample(f_name, resample_intvl, clean_data_dir):
"""
重采样
"""
car_vin = os.path.basename(f_name).split('.')[0].split('_')[0]
df = pd.read_feather(f_name)
运行结果:
df_raw shape: (20712, 172)
2022-01-22 10:51:07.282897 del_not_need_col start running.
2022-01-22 10:51:07.404211 del_not_need_col done.
del_not_need_col total use time: 0:00:00.121314
2022-01-22 10:51:07.404254 extract_feature start running.
2022-01-22 10:51:07.404262 clean_data start running.
2022-01-22 10:51:11.548022 clean_data done.
clean_data total use time: 0:00:04.143760
2022-01-22 10:51:11.548087 add_basic_features start running.
2022-01-22 10:51:12.081558 add_basic_features done.
add_basic_features total use time: 0:00:00.533471
2,使用函数装饰器实现单例模式
def singleton(cls, *args, **kw):
"""
单例模式的类装饰器:在整个项目的运行周期内只有一个实例。
"""
instance = {}
def _singleton():
if cls not in instance:
instance[cls] = cls(*args, **kw)
return instance[cls]
return _singleton
使用方法:
@singleton
class InitParas(object):
"""
初始化参数配置
"""
def __init__(self):
self.NUM_CELLS = 28 # 电芯电压数量
self.NUM_ETPD = 6 # 电芯温度数量