Introduction
Dans ce laboratoire, vous serez transporté dans un ciel nocturne magique où vous êtes un voyageur interstellaire en quête de maîtriser le pouvoir des gestionnaires de contexte Python. Dans ce scénario enchanté, vous explorerez les mystères profonds de la gestion de contexte tout en naviguant parmi les étoiles scintillantes et les merveilles célestes.
Création d'un gestionnaire de contexte
Dans cette étape, vous créerez un gestionnaire de contexte Python dans /home/labex/project/context_manager.py pour encapsuler un ensemble d'opérations. Voici un exemple de gestionnaire de contexte qui simule un portail interstellaire :
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")
## Exemple d'utilisation
with InterstellarPortal():
print("Stepping into the interstellar portal")
Exécutez le script :
python context_manager.py
Les informations suivantes devraient s'afficher sur votre terminal :
Opening the portal to another dimension
Stepping into the interstellar portal
Closing the portal
Gérer les exceptions dans un gestionnaire de contexte
Dans cette étape, vous allez améliorer le gestionnaire de contexte pour gérer les exceptions qui peuvent se produire à l'intérieur du contexte. Regardez le gestionnaire de contexte InterstellarPortal modifié.
Dans /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}")
## Exemple d'utilisation
with InterstellarPortal():
print("Stepping into the interstellar portal")
1 / 0 ## Simulate an error
Exécutez le script :
python context_manager.py
Les informations suivantes devraient s'afficher sur votre terminal :
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
Résumé
Dans ce laboratoire, vous avez exploré le monde enchanté des gestionnaires de contexte Python en créant votre propre gestionnaire de contexte de portail interstellaire et en l'améliorant pour gérer avec grâce les exceptions. Ce voyage vous permettra de maîtriser les pouvoirs mystiques de la gestion de contexte et de approfondir votre compréhension des fonctionnalités élégantes de Python. Bonne programmation interstellaire!



