Python: Surcharge: Difference between revisions
Jump to navigation
Jump to search
Wiki-cours (talk | contribs) No edit summary |
Wiki-cours (talk | contribs) |
||
Line 148: | Line 148: | ||
<source lang="python"> | <source lang="python"> | ||
class Temps: | class Temps: | ||
def __init__(self,h=0,m=0,s=0): | def __init__(self,h=0,m=0,s=0): | ||
self.heure = h | self.heure = h |
Revision as of 23:30, 19 November 2015
Méthodes d'affichage
utilisation | nom |
---|---|
conversion en string pour print | __str__(self) |
affichage | __repr__(self) |
Opérations mathématiques
Définir ou redéfinir les opérateurs standards permet d'utiliser les symboles mathématiques pour de nouveaux objets:
opération | symbole | méthode | symbole unaire | méthode |
---|---|---|---|---|
addition | + | __add__(self,other) | += | __iadd__(self,other) |
soustraction | - | __sub__(self,other) | -= | __isub__(self,other) |
multiplication | * | __mul__(self,other) | *= | __imul__(self,other) |
division | / | __truediv__(self,other) | /= | __itruediv__(self,other) |
élévation à la puissance | ** | __pow__(self,other) | **= | __ipow__(self,other) |
division entière | // | __floordiv__(self,other) | //= | __ifloordiv__(self,other) |
reste de la division entière (modulo) | % | __mod__(self,other) | %= | __imod__(self,other) |
opération | symbole | méthode |
---|---|---|
opposé | - | __neg__(self) |
positif | + | __pos__(self) |
valeur absolue | abs() | __abs__(self) |
Opérateurs de comparaison
opération | symbole | méthode |
---|---|---|
égal | == | __eq__(self,other) |
non égal | != ou <> | __ne__(self,other) |
strictement inférieur | < | __lt__(self,other) |
strictement supérieur | > | __gt__(self,other) |
inférieur ou égal | <= | __le__(self,other) |
supérieur ou égal | >= | __ge__(self,other) |
comparaison | __cmp__(self,other) |
Opérateurs de conteneurs
destinés à des objets pouvant être des conteneurs
opération | syntaxe | méthode |
---|---|---|
dimension | len(objet) | __len__(self) |
accès aux éléments en lecture | objet[key] | __getitem__(self,key) |
accès aux éléments en écriture | objet[key] | __setitem__(self,key,value) |
Un exemple
Une classe qui gère l'affiche de l'heure en temps (pas réaliste mais montre bien l'encapsulation des données et la surcharge):
class Temps:
def __init__(self,h=0,m=0,s=0):
self.heure = h
self.minute = m
self.seconde = s
def __str__(self):
return str(self.heure)+'h' \
+ str(self.minute)+'mn' \
+ str(self.seconde)+'s'
def __add__(self,other):
if not other.__class__ is Temps:
print "Erreur: l'argument n'est pas un Temps"
return NotImplemented
res = Temps()
res.seconde = (self.seconde+other.seconde)%60
res.minute = (self.minute+other.minute + (self.seconde+other.seconde)//60)%60
res.heure = self.heure+other.heure + (self.minute+other.minute)//60
return res
t1,t2 = Temps(1,24,48), Temps(0,52,32)
print t1, t2, t1+t2