Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ 実際のアプリケーションにおけるPythonデコレータの実用例 | Pythonデコレータの習得
Pythonにおける関数型プログラミングの概念

book実際のアプリケーションにおけるPythonデコレータの実用例

メニューを表示するにはスワイプしてください

Pythonのデコレータは、関数やメソッドの動作を変更するための強力なツール。 最も一般的な用途は、スリープ処理、実行時間の検証、ロギング。

1. スリーピングデコレータ

このデコレータは、関数の実行前に指定した時間だけ待機。

1234567891011121314151617
import time def sleep_decorator(seconds): def decorator(func): def wrapper(*args, **kwargs): print(f"Sleeping for {seconds} seconds before executing '{func.__name__}'") time.sleep(seconds) return func(*args, **kwargs) return wrapper return decorator @sleep_decorator(2) def my_function(): print("Function executed!") # Usage my_function()
copy

2. バリデーションデコレーター

このデコレーターは、関数への入力が特定の条件を満たしているかどうかを確認。

1234567891011121314151617
def validate_decorator(func): def wrapper(number): if not isinstance(number, int) or number < 0: raise ValueError("Input must be a non-negative integer") return func(number) return wrapper @validate_decorator def factorial(n): if n == 0: return 1 else: return n * factorial(n - 1) # Usage print(factorial(5)) # factorial(-1) # This will raise an error
copy

3. タイミングデコレーター

このデコレーターは関数の実行時間を計測します。前の章ですでに使用しました。

12345678910111213141516171819
import time def timing_decorator(func): def wrapper(*args, **kwargs): start_time = time.time() result = func(*args, **kwargs) end_time = time.time() print(f"'{func.__name__}' executed in {end_time - start_time} seconds") return result return wrapper @timing_decorator def some_function(): time.sleep(1) # Simulating a task print("Function completed") # Usage some_function()
copy

ログイン認証用のデコレーターは追加のライブラリを使用し、ウェブサイト開発で利用されるため、ウェブサイト作成の文脈でこのデコレーターを考えるのがより適切です。

前述の通り、デコレーターはPythonにおいて複雑なトピックであり、十分に理解するにはさらなる実践が必要な場合があります。プログラマーの思考法を身につけるための正しい道を進んでいます。

コースのノートをダウンロードしてください。😉

1. 次のコードの出力は何ですか?

2. 次のコードの出力は何ですか?

question mark

次のコードの出力は何ですか?

正しい答えを選んでください

question mark

次のコードの出力は何ですか?

正しい答えを選んでください

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 5.  7

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 5.  7
some-alt