17.12.2012 Views

Programmation PYTHON - Zenk - Security - Repository

Programmation PYTHON - Zenk - Security - Repository

Programmation PYTHON - Zenk - Security - Repository

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Structuration du code<br />

CHAPITRE 5<br />

Pour toutes ces méthodes, un appel à objet opérateur other déclenche un appel à<br />

objet.methode(other).<br />

La variation I ajoute un préfixe i à la méthode (__iadd__(), __imul__(), etc.) et<br />

permet de définir les opérateurs augmentés +=, *=, etc. Cette variation renvoie en<br />

général objet augmenté de other.<br />

La variation R ajoute un préfixe r à la méthode (__radd__(), __rmul__(), etc.) et<br />

permet de définir des opérateurs inversés : other.operateur(object) est appelé en<br />

lieu et place de objet.operateur(other). Lorsque l’opération classique n’est pas<br />

supportée, l’interpréteur tente l’opération inverse.<br />

Surcharge de l’addition<br />

Tableau 5–1 Méthodes pour les opérateurs numériques (suite)<br />

Méthode Opération Variations<br />

__truediv__(other) objet / other R et I<br />

__neg__() - objet<br />

__pos__() + objet<br />

__abs__() abs(objet)<br />

__invert__() ~ objet<br />

__complex__() complex(objet)<br />

__int__() int(objet)<br />

__long__() long(objet)<br />

__float__() float(objet)<br />

__oct__() oct(objet)<br />

__hex__() hex(objet)<br />

__coerce__(other) coerce(objet, other)<br />

>>> class Additionable:<br />

... def __init__(self, value):<br />

... self.value = value<br />

... def __add__(self, other):<br />

... return Additionable(self.value + other.value )<br />

... def __iadd__(self, other):<br />

... return self.__add__(other)<br />

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

... return str(self.value)<br />

...<br />

>>> val1 = Additionable(5)<br />

>>> val2 = Additionable(12)<br />

>>> val3 = val1 + val2<br />

>>> str(val3)<br />

'17'<br />

125

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

Saved successfully!

Ooh no, something went wrong!