** 背景**:在学习装饰器中遇到问题
** 环境**:以下代码均为windows版anaconda3中执行的代码
问题:尽管已经实践过并且没有找到可行的方法,但是我仍然想问,为什么不将logit和logging_decorator这两个函数合一,变成类似第二段代码的样式?我目前理解装饰器的核心是闭包,但是为什么不尽量减少闭包的数量,将功能尽并到一起?是因为无法实现吗?
标准代码
from functools import wraps
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()
def myfunc1():
pass
myfunc1()
# Output: myfunc1 was called
# 现在一个叫做 out.log 的文件出现了,里面的内容就是上面的字符串
- 我的设想(该代码会报错,仅用于注解猜想)
from functools import wraps
def logging_decorator(func,logfile=''out.log):
@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
@logging_decorator(logfile='out.log')
def myfunc1():
pass
myfunc1()
# Output: myfunc1 was called
# 现在一个叫做 out.log 的文件出现了,里面的内容就是上面的字符串