Intermédiaire
🧠 Fondamentaux
20 XP
0 personnes ont réussi
Dataclass basique
En Python, quand tu créés une classe avec des attributs, tu dois écrire __init__, __repr__, __eq__... C'est beaucoup de code repetitif. Le decorateur @dataclass génère tout ca automatiquement a partir de simples annotations de type.
Avant (classique) :
class Point: def __init__(self, x, y): self.x = x self.y = y def __repr__(self): return f'Point(x={self.x}, y={self.y})' def __eq__(self, other): return self.x == other.x and self.y == other.y
Apres (dataclass) :
from dataclasses import dataclass
@dataclass class Point: x: float y: float
Tu declares les champs avec des annotations de type (x: float), et Python génère __init__, __repr__ et __eq__ pour toi. Tu peux toujours ajouter tes propres méthodes.
Crée une dataclass Point avec deux attributs x: float et y: float. Ajoute une méthode distance_origine() qui retourne la distance au point (0, 0), c'est-a-dire racine carree de (x au carre + y au carre).
Exemple : Point(3.0, 4.0).distance_origine() # renvoie 5.0 Point(1.0, 2.0) == Point(1.0, 2.0) # renvoie True (grace a __eq__ genere)
Tests (3/4)
Création
p = Point(3.0, 4.0)
assert p.x == 3.0 and p.y == 4.0
Distance
assert Point(3.0, 4.0).distance_origine() == 5.0
Égalité auto
assert Point(1.0, 2.0) == Point(1.0, 2.0)
+ 0 tests cachés
Indices (3 disponibles)
Solution officielle
from dataclasses import dataclass
import math
@dataclass
class Point:
x: float
y: float
def distance_origine(self):
return math.sqrt(self.x ** 2 + self.y ** 2)