17.12.2012 Views

Programmation PYTHON - Zenk - Security - Repository

Programmation PYTHON - Zenk - Security - Repository

Programmation PYTHON - Zenk - Security - Repository

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

94<br />

Éléments du langage<br />

DEUXIÈME PARTIE<br />

Déclenchement d’une erreur<br />

>>> class CatchTypeError(object):<br />

... def __enter__(self):<br />

... print('debut')<br />

... def __exit__(self, exc_type, exc_value, traceback):<br />

... print('fin')<br />

... if exc_type == TypeError:<br />

... return True<br />

... return False<br />

...<br />

>>> c = CatchTypeError()<br />

>>> with c:<br />

... raise TypeError()<br />

...<br />

debut<br />

fin<br />

>>> with c:<br />

... raise AttributeError()<br />

...<br />

debut<br />

fin<br />

Traceback (most recent call last):<br />

File "", line 2, in <br />

AttributeError<br />

Enfin, si une erreur survient dans la méthode __exit__, elle prévaudra sur toute<br />

erreur précédente.<br />

Lorsque l’objet utilisé est initialisé directement, une directive as peut être associée à with<br />

Écriture dans un fichier<br />

>>> with open('fichier', 'w') as f:<br />

... f.write('contenu')<br />

Dans ce cas, f se voit attribuer la valeur renvoyée par __enter__. L’usage le plus courant<br />

est donc de renvoyer self dans cette méthode.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!