Classes & POO
Python ↔ Baobab
11 correspondances
Le constructeur __init__ s'appelle nouveau, self s'appelle ce, super() s'appelle parent(). L'héritage, la surcharge et les attributs de classe suivent le modèle Python.
| Python | Baobab | Description |
|---|---|---|
| class Animal: | classe Animal: | Déclaration d'une classe. |
| def __init__(self, …): | fonction nouveau(…): | Constructeur, appelé à l'instanciation. |
| self | ce | Référence à l'instance courante. |
| self.nom = nom | ce.nom = nom | Attribut d'instance. |
| a = Animal("Rex") | a = nouveau Animal("Rex") | Instanciation d'un objet. |
| def parler(self): … | fonction parler(): … | Méthode d'instance (ce est implicite en Baobab). |
| class Chien(Animal): | classe Chien(Animal): | Héritage : Chien étend Animal. |
| super().__init__(…) | parent().nouveau(…) | Appelle le constructeur de la classe mère. |
| def __str__(self): … | fonction _texte_(): … | Représentation textuelle utilisée par afficher(). |
| compteur = 0 (dans la classe) | compteur = 0 | Attribut de classe, partagé par toutes les instances. |
| isinstance(rex, Animal) | est_instance(rex, Animal) | Test du type d'un objet (héritage inclus). |
Exemple complet - Baobab ↔ Python
Baobab
123456789101112131415161718192021222324252627classe Animal:
fonction nouveau(nom):
ce.nom = nom
fonction parler():
retourner "..."
fonction _texte_():
retourner f"Animal({ce.nom})"
classe Chien(Animal):
fonction nouveau(nom, race):
parent().nouveau(nom) # super().__init__
ce.race = race
fonction parler(): # surcharge
retourner f"{ce.nom} dit Wouf !"
rex = nouveau Chien("Rex", "berger")
afficher(rex.parler()) # → Rex dit Wouf !
afficher(rex.race) # → berger
afficher(est_instance(rex, Animal)) # → vrai (héritage)
# Polymorphisme
animaux = [nouveau Chien("Rex", "berger"), nouveau Animal("Mystère")]
pour a dans animaux:
afficher(a.parler())Python
123456789101112131415161718192021222324252627class Animal:
def __init__(self, nom):
self.nom = nom
def parler(self):
return "..."
def __str__(self):
return f"Animal({self.nom})"
class Chien(Animal):
def __init__(self, nom, race):
super().__init__(nom)
self.race = race
def parler(self): # override
return f"{self.nom} dit Wouf !"
rex = Chien("Rex", "berger")
print(rex.parler()) # → Rex dit Wouf !
print(rex.race) # → berger
print(isinstance(rex, Animal)) # → True (inheritance)
# Polymorphism
animaux = [Chien("Rex", "berger"), Animal("Mystère")]
for a in animaux:
print(a.parler())