python 之 帶引數的裝飾器
阿新 • • 發佈:2018-12-26
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 的檔案出現了,裡面的內容就是上面的字串
@logit(logfile='func2.log')
def myfunc2():
pass
myfunc2()
# Output: myfunc2 was called
# 現在一個叫做 func2.log 的檔案出現了,裡面的內容就是上面的字串