本文参考了
装饰器的实质是把函数当做参数传递给另一个函数(装饰函数)并返回。 先看一个简单的例子:
from functools import wrapsdef logit(func): @wraps(func) def with_logging(*args, **kwargs): print(func.__name__ + " was called") return func(*args, **kwargs) return with_logging@logitdef addition_func(x): """Do some math.""" return x + xresult = addition_func(4)# Output: addition_func was called
再看下带参数的装饰器:
def logit(logfile='out.log'): def logging_decorator(func): @wraps(func) def wrapped_function(*args, **kwargs): log_string = func.__name__ + " was called" print(log_string) # 打开logfile,并写入内容 with open(logfile, 'a') as opened_file: # 现在将日志打到指定的logfile opened_file.write(log_string + '\n') return func(*args, **kwargs) return wrapped_function return logging_decorator@logit(logfile='func2.log')def myfunc2(): passmyfunc2()