مرکزی مواد پر جائیں
eLearner.app
ماڈیول 9 · سبق 2 از 4کورس میں 34/36~12 min
ماڈیول اسباق (2/4)

ڈیٹا کلاس: بوائلر پلیٹ کے بغیر ڈیٹا کلاسز

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 کوششوں کے بعد حل دستیاب ہے۔