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.

PythonBaobabDescription
class Animal:classe Animal:Déclaration d'une classe.
def __init__(self, …):fonction nouveau(…):Constructeur, appelé à l'instanciation.
selfceRéférence à l'instance courante.
self.nom = nomce.nom = nomAttribut 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 = 0Attribut 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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
classe 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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class 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())