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.

PythonBaobabDescription
class Animal:classe Animal:Declare a class.
def __init__(self, …):fonction nouveau(…):Constructor, called at instantiation.
selfceReference to the current instance.
self.nom = nomce.nom = nomInstance 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 = 0Class attribute, shared by all instances.
isinstance(rex, Animal)est_instance(rex, Animal)Object type test (inheritance included).
Complete example — 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())