from functools import wraps
class logit():
def __init__(self, logfile='out.log'):
self.log = logfile
def __call__(self, func):
@wraps(func)
def wrapper(*args, **kwargs):
# args 为元组;kwargs 为字典
info = func.__name__ + "was called"
with open(self.log, 'rw') as f:
f.write(info)
self.notify()
# 把传递进来的参数元组 args 和 参数字典 kwargs 展开,并调用原始函数
return func(*args, **kwargs)
return wrapper
def notify(self):
# TODO send email
pass
def func1(arg1, arg2):
print arg1, arg2
# 不使用装饰器
func = logit('test.log')(func1)
func(1, 2)
#使用装饰器
@logit('test.log')
def func2(arg1, arg2):
print arg1, arg2
func2(3, 4)