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.

110<br />

Éléments du langage<br />

DEUXIÈME PARTIE<br />

Si on ajoute des print pour mettre en valeur l’enchaînement :<br />

Enchaînement d’un decorator paramétré<br />

>>> def only_int(function):<br />

...print('appel de only_int')<br />

... def _only_int(arg):<br />

... ifnot isinstance(arg, int):<br />

... raise TypeError("'%s' doit être un int" % str(arg))<br />

... return function(arg)<br />

... print('renvoi de _only_int')<br />

... return _only_int<br />

...<br />

>>> def only_long(function):<br />

... print('renvoi de only_long')<br />

... def _only_long(arg):<br />

... ifnot isinstance(arg, long):<br />

... raise TypeError("'%s' doit être un long" % str(arg))<br />

... return function(arg)<br />

... print('renvoi de _only_long')<br />

... return _only_long<br />

...<br />

>>> def int_or_long(force_long):<br />

... print('appel de int_or_long')<br />

... if force_long:<br />

... print('renvoi de only_long')<br />

... return only_long<br />

... else:<br />

... print('renvoi de only_int')<br />

... return only_int<br />

...<br />

>>> @int_or_long(True)<br />

... def function(entier):<br />

... return entier + 1<br />

...<br />

appel de int_or_long<br />

renvoi de only_long<br />

appel de only_long<br />

renvoi de _only_long<br />

>>> function(56L)<br />

57L<br />

AVENIR Émergence des decorators<br />

Les patterns d’utilisation des decorators émergent actuellement des travaux des développeurs de la communauté.<br />

Il est possible qu’à terme Python propose une liste étendue de decorators.

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

Saved successfully!

Ooh no, something went wrong!