Python コンテキストマネージャー

PythonPythonBeginner
今すぐ練習

💡 このチュートリアルは英語版からAIによって翻訳されています。原文を確認するには、 ここをクリックしてください

はじめに

この実験では、あなたは魔法の夜空に運ばれ、Pythonコンテキストマネージャーの力を利用する探求の旅に出る惑星間旅行者になります。この魅力的なシナリオでは、きらめく星や天体の不思議を探索しながら、コンテキスト管理の深い謎を探ります。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/AdvancedTopicsGroup(["Advanced Topics"]) python/AdvancedTopicsGroup -.-> python/context_managers("Context Managers") subgraph Lab Skills python/context_managers -.-> lab-271535{{"Python コンテキストマネージャー"}} end

コンテキストマネージャーの作成

このステップでは、/home/labex/project/context_manager.py にPythonのコンテキストマネージャーを作成して、一連の操作をカプセル化します。以下は、惑星間ポータルをシミュレートするコンテキストマネージャーの例です。

class InterstellarPortal:
    def __enter__(self):
        print("Opening the portal to another dimension")

    def __exit__(self, exc_type, exc_val, exc_tb):
        print("Closing the portal")

## Example usage
with InterstellarPortal():
    print("Stepping into the interstellar portal")

スクリプトを実行します。

python context_manager.py

端末に以下の情報が表示されるはずです。

Opening the portal to another dimension
Stepping into the interstellar portal
Closing the portal

コンテキストマネージャーにおける例外処理

このステップでは、コンテキスト内で発生する可能性のある例外を処理するようにコンテキストマネージャーを強化します。修正されたInterstellarPortalコンテキストマネージャーを見てみましょう。

/home/labex/project/context_manager.py 内:

class InterstellarPortal:
    def __enter__(self):
        print("Opening the portal to another dimension")

    def __exit__(self, exc_type, exc_val, exc_tb):
        print("Closing the portal")
        if exc_type is not None:
            print(f"An error occurred: {exc_type}, {exc_val}")

## Example usage
with InterstellarPortal():
    print("Stepping into the interstellar portal")
    1 / 0  ## Simulate an error

スクリプトを実行します。

python context_manager.py

端末に以下の情報が表示されるはずです。

Opening the portal to another dimension
Stepping into the interstellar portal
Closing the portal
An error occurred: <class 'ZeroDivisionError'>, division by zero
Traceback (most recent call last):
  File "/home/labex/project/context_manager.py", line 13, in <module>
    1 / 0  ## Simulate an error
ZeroDivisionError: division by zero

まとめ

この実験では、独自の惑星間ポータルコンテキストマネージャーを作成し、例外を円滑に処理するように強化することで、Pythonのコンテキストマネージャーの魅力的な世界を探索しました。この旅は、あなたにコンテキスト管理の神秘的な力を利用し、Pythonのエレガントな機能の理解を深める力を与えます。惑星間コーディングを楽しんでください!