2. CLASSE
UML + Python
Attribut:
chaque CompteCourant a le sien
Opération:
chaque CompteCourant sait le faire
Sylvain Leroux – www.chicoree.fr – 2009 – Licence CC-BY3.0
3. CLASSE
UML + Python
class CompteCourant(object):
def __init__(self):
# A la création, le solde est à zéro
self.solde = 0 # Solde en cents!
def crediter(self, montant):
self.solde += montant
def debiter(self, montant):
if self.solde < montant:
raise OperationRejetee();
self.solde -= montant
Sylvain Leroux – www.chicoree.fr – 2009 – Licence CC-BY3.0
4. INTERFACE
UML + Python
Tous les Comptes possèdent les
mêmes opérations
Sylvain Leroux – www.chicoree.fr – 2009 – Licence CC-BY3.0
5. INTERFACE
UML + Python
Python est dynamique
Pas besoin de coder les interfaces
class CompteSurLivret(object):
def __init__(self, plafond):
# ...
# ...
class CompteCourant(object):
def __init__(self):
# ...
# ...
Sylvain Leroux – www.chicoree.fr – 2009 – Licence CC-BY3.0
6. INTERFACE – option 1
UML + Python
class Compte(object):
Créer un stub def crediter(self, montant):
pass
pour l'interface def debiter(self, montant):
pass
class CompteSurLivret(Compte):
def __init__(self, plafond):
# ...
Faire hériter # ...
les classes class CompteCourant(Compte):
def __init__(self):
# ...
# ...
Sylvain Leroux – www.chicoree.fr – 2009 – Licence CC-BY3.0
7. INTERFACE – option 2
UML + Python
class Compte(object):
Variante avec def crediter(self, montant):
raise NonMisEnOeuvre()
exceptions def debiter(self, montant):
raise NonMisEnOeuvre()
class CompteSurLivret(Compte):
def __init__(self, plafond):
# ...
Faire hériter # ...
les classes class CompteCourant(Compte):
def __init__(self):
# ...
# ...
Sylvain Leroux – www.chicoree.fr – 2009 – Licence CC-BY3.0
8. HÉRITAGE
Quand la classe de base fait
UML + Python
quelquechose d'utile, on parle
d'héritage
class Compte(object):
def afficheSolde(self):
print "%+10.2f" % (self.solde / 100.0)
# ...
class CompteSurLivret(Compte):
# ...
if __name__ == '__main__':
compte = CompteSurLivret(10000)
compte.crediter(10000)
compte.afficheSolde()
Sylvain Leroux – www.chicoree.fr – 2009 – Licence CC-BY3.0
9. AGRÉGATION
UML + Python
Chaque Client
possède un Compte
class Client(object):
def __init__(self, compte):
self.compte = compte
if __name__ == '__main__':
# John possède un compte courant
john = Client( CompteCourant() )
# Paul possède un compte sur livret
paul = Client( CompteSurLivret(5000000) )
Sylvain Leroux – www.chicoree.fr – 2009 – Licence CC-BY3.0
10. AGRÉGATION
UML + Python
class Client(object):
def __init__(self):
self.compte = []
def ajouteCompte(self, compte):
self.compte.append(compte)
if __name__ == '__main__':
ringo = Client()
ringo.ajouteCompte( CompteCourant() )
ringo.ajouteCompte( CompteCourant(5000000) )
Chaque Client
possède des Comptes
Sylvain Leroux – www.chicoree.fr – 2009 – Licence CC-BY3.0