Classes & OOP
Python ↔ Baobab
11 correspondences
The __init__ constructor is called nouveau, self is ce, super() is parent(). Inheritance, overriding and class attributes follow the Python model.
| Python | Baobab | Description |
|---|---|---|
| class Animal: | classe Animal: | Declare a class. |
| def __init__(self, …): | fonction nouveau(…): | Constructor, called at instantiation. |
| self | ce | Reference to the current instance. |
| self.nom = nom | ce.nom = nom | Instance attribute. |
| a = Animal("Rex") | a = nouveau Animal("Rex") | Instantiate an object. |
| def parler(self): … | fonction parler(): … | Instance method (ce is implicit in Bao). |
| class Chien(Animal): | classe Chien(Animal): | Inheritance: Chien extends Animal. |
| super().__init__(…) | parent().nouveau(…) | Call the parent class constructor. |
| def __str__(self): … | fonction _texte_(): … | Text representation used by afficher(). |
| compteur = 0 (dans la classe) | compteur = 0 | Class attribute, shared by all instances. |
| isinstance(rex, Animal) | est_instance(rex, Animal) | Object type test (inheritance included). |
Complete example — 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())