from functools import wraps from datetime import datetime #类的装饰器写法,日志 class log(object): def __init__(self, logfile='F:\log.txt'): self.logfile = logfile def __call__(self, func): @wraps(func) def wrapped_func(*args, **kwargs): self.writeLog(*args, **kwargs) # 先调用 写入日志 return func(*args, **kwargs) # 正式调用主要处理函数 return wrapped_func #写入日志 def writeLog(self, *args, **kwargs): time = datetime.now().strftime("%Y-%m-%d %H:%M:%S") log_str = time+' 操作人:{0[0]} 进行了【{0[1]}】操作'.format(args) with open(self.logfile, 'a') as file: file.write(log_str + '\n') @log() def myfunc(name,age): print('姓名:{0},年龄:{1}'.format(name,age)) if __name__ == '__main__': myfunc('小白', '查询') myfunc('root', '添加人员') myfunc('小小', '修改数据')
python 装饰器之类装饰器
最新推荐文章于 2024-08-30 11:16:31 发布
