Exercices POO La méthode __str__
🎉

Bravo!

Débutant 🧠 Fondamentaux 10 XP 0 personnes ont réussi

La méthode __str__

Quand tu fais print() sur un objet, Python cherche une méthode speciale appelee __str__ pour savoir comment l'afficher. Sans cette méthode, tu obtiens quelque chose comme '<__main__.Personne object at 0x...>', ce qui n'est pas tres utile.

En definissant __str__, tu controles ce que print() affiche :

class Personne:
def __init__(self, nom, age):
self.nom = nom
self.age = age

def __str__(self):
return self.nom + ' a ' + str(self.age) + ' ans'

p = Personne('Alice', 30)
print(p) affiche 'Alice a 30 ans'
str(p) renvoie 'Alice a 30 ans'

Attention : __str__ doit toujours renvoyer une chaine (str). Si tu as un nombre, convertis-le avec str().

Crée une classe Produit avec un nom et un prix. Definis __str__ pour qu'elle renvoie 'nom : prix EUR' (le prix avec 2 decimales).

Exemple :
p = Produit('Cafe', 4.5)
str(p) renvoie 'Cafe : 4.50 EUR'

Tests (3/4)

Cafe
p = Produit('Cafe', 4.5)
assert str(p) == 'Cafe : 4.50 EUR'
Gratuit
p = Produit('Echantillon', 0)
assert str(p) == 'Echantillon : 0.00 EUR'
Prix entier
p = Produit('Livre', 25)
assert str(p) == 'Livre : 25.00 EUR'

+ 0 tests cachés

Indices (3 disponibles)

solution.py