0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Python】クラスで簡単なデコレータを作成してみる

Posted at

内容

関数実行時に以下の内容を出力するデコレータをクラスで定義する

  • 関数開始メッセージ
  • 関数実行時の引数
  • 関数終了メッセージ
  • 関数実行にかかった時間

実装

from time import *

class logger:
    def __init__(self, func):
        self.func = func
    def __call__(self, *args):
        # 関数開始メッセージ
        print(f"--- {self.func.__name__} start ---")
        # 関数実行時の引数
        print(f"--- args: {args} ---")
        start = time()
        ret = self.func(*args)
        difftime = time() - start
        # 関数終了メッセージ
        print(f"--- {self.func.__name__} end ---")
        # 関数実行にかかった時間
        print(f"--- execute time: {difftime} ---")

        return ret

@logger
def add(a, b):
    # 3秒待機
    sleep(3)
    return a+b

print(add(3, 5))

結果

--- add start ---
--- args: (3, 5) ---
--- add end ---
--- execute time: 3.0143697261810303 ---
8

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?