- 在函数中嵌入装饰器
在函数中嵌入装饰器
我们回到日志的例子,并创建一个包裹函数,能让我们指定一个用于输出的日志文件。
from functools import wrapsdef 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:# 现在将日志打到指定的logfileopened_file.write(log_string + '\n')return func(*args, **kwargs)return wrapped_functionreturn logging_decorator@logit()def myfunc1():passmyfunc1()# Output: myfunc1 was called# 现在一个叫做 out.log 的文件出现了,里面的内容就是上面的字符串@logit(logfile='func2.log')def myfunc2():passmyfunc2()# Output: myfunc2 was called# 现在一个叫做 func2.log 的文件出现了,里面的内容就是上面的字符串
