How to use Python Decorators_1

加入了寫入Log文件的Decorators:

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 的文件出現了,裏面的內容就是上面的字符串

注意下Return順序:

  1. Function
  2. Function_Operation
  3. Others
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章