我正在嘗試學習如何製作我自己的裝飾器。我不明白如何「調用」正在封裝的函數內部的數據。如何製作一個檢查變量是否存在的裝飾器?
我想做一個非常簡單的裝飾器,將msg的值寫入文本文件。
def logging(f):
def decorator(args, **kwargs):
debug_file = "/tmp/easylog.txt"
fh = open(debug_file, 'a')
fh.write(f.message + "\n")
fh.close()
return decorator
@logging
def test(a,b):
c=a+b
message = "hello test"
return c
test(4,5)
所以我不明白該怎麼做的部分是檢查裝飾器內的消息。
在我讀過的所有基本教程中,它展示瞭如何獲取整個返回值並以粗體顯示或者其他內容,我正在嘗試學習如何獲取各個值並操作它們。
另外,我知道Python已經內置了日誌記錄機制,但爲了學習,我想弄清楚這個例子。 – david