python用类写装饰器

2017-06-16  本文已影响0人  阿古瓜
代码示例
# -*- coding:utf-8 -*-
from functools import wraps
from datetime import datetime

#类的装饰器写法,日志
class log(object):
    def __init__(self, logfile='c:\out.log'):
        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',encoding='utf8') 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('小小', '修改数据')

日志己保存于指定位置,打开内容如下:
log.png
上一篇 下一篇

猜你喜欢

热点阅读