דילוג לתוכן המרכזי
eLearner.app
מודול 9 · שיעור 2 מתוך 434/36 בקורס~12 min
שיעורי מודול (2/4)

dataclass: מחלקות נתונים ללא לוחית

The @dataclass decorator (dataclasses module) automatically generates __init__, __repr__, and __eq__ for classes whose only job is to hold data. Less boilerplate, clearer code.

Without dataclass (boilerplate)

Python
class Punto:
    def __init__(self, x: float, y: float) -> None:
        self.x = x
        self.y = y
    def __repr__(self) -> str:
        return f"Punto(x={self.x}, y={self.y})"
    def __eq__(self, other) -> bool:
        if not isinstance(other, Punto):
            return NotImplemented
        return (self.x, self.y) == (other.x, other.y)

With dataclass

Python
from dataclasses import dataclass

@dataclass
class Punto:
    x: float
    y: float

p = Punto(3, 4)
p             # Punto(x=3, y=4)   ← __repr__ gratis
Punto(3, 4) == Punto(3, 4)        # True ← __eq__ gratis
p.x, p.y      # 3, 4

The pattern: declare fields as class annotations (name: type), optionally with a default value. @dataclass generates the rest.

Default and default_factory

Python
from dataclasses import dataclass, field

@dataclass
class Articolo:
    nome: str
    prezzo: float = 0.0
    tag: list[str] = field(default_factory=list)

frozen=True: immutable

Python
@dataclass(frozen=True)
class Coordinata:
    lat: float
    lon: float

c = Coordinata(45.4, 9.2)
c.lat = 99   # FrozenInstanceError!

frozen dataclasses are also hashable: you can use them as dict keys or set elements.

order=True: automatic comparisons

Python
@dataclass(order=True)
class Voto:
    valore: int

Voto(10) < Voto(20)   # True
sorted([Voto(30), Voto(10), Voto(20)])

Generates __lt__, __le__, __gt__, __ge__ comparing fields in the order they were declared.

Normal methods

Dataclasses remain regular classes: you can add methods.

Python
import math
from dataclasses import dataclass

@dataclass
class Punto:
    x: float
    y: float
    def distanza_dall_origine(self) -> float:
        return math.hypot(self.x, self.y)

Punto(3, 4).distanza_dall_origine()   # 5.0

Immutable and efficient dataclasses

You can make a dataclass immutable by passing the argument frozen=True to the decorator: @dataclass(frozen=True). This raises an error on any attempt to mutate attributes after instantiation, making instances safe for concurrent environments or for use as dictionary keys.

Try it yourself

פעילות גופנית#python.m9.l2.e1
ניסיונות: 0טוען...

Create a dataclass `Book` with fields `title: str` and `pages: int`. Instantiate it as `l = Book('Moby Dick', 635)`. Evaluate `l == Book('Moby Dick', 635)`.

טוען עורך...
הצג רמז

@dataclass generates __eq__ comparing field by field.

הפתרון זמין לאחר 3 ניסיונות

Review exercise

פעילות גופנית#python.m9.l2.e2
ניסיונות: 0טוען...

Create a dataclass `Basket` with field `items: list[str]` with default_factory=list. Instantiate `c1 = Basket()` and `c2 = Basket()`, append 'mela' to c1.items. Evaluate `(c1.items, c2.items)` to verify they are NOT the same list.

טוען עורך...
הצג רמז

field(default_factory=list) guarantees a new list per instance.

הפתרון זמין לאחר 3 ניסיונות

Additional challenge

פעילות גופנית#python.m9.l2.e3
ניסיונות: 0טוען...

Import `dataclass` from `dataclasses`. Create a dataclass `Point` containing two float coordinates `x` and `y`. Instantiate a point with `x=1.5` and `y=2.5` storing it in `p`. Finally, evaluate `p`.

טוען עורך...
הצג רמז

Use @dataclass above the class Point, and declare x: float and y: float.

הפתרון זמין לאחר 3 ניסיונות