CKTIS / Python
Rekordy i agregaty
Rekord opisuje pojedynczy wiersz nazwanymi polami, a agregat łączy wyniki wielu wierszy.
Wersja: Python 3.14; repository image, production runtime not attested
Składnia
@dataclass(frozen=True)Rekord opisuje pojedynczy wiersz nazwanymi polami, a agregat łączy wyniki wielu wierszy.
Dataclass generuje inicjalizację i równość, lecz adnotacje nie walidują argumentów. Przykład sprawdza dodatnią całkowitą ilość po inicjalizacji, po czym sumuje iloczyny ceny w groszach i ilości.
Pusty zbiór wierszy daje sumę zero.
Przykłady
from dataclasses import dataclass
@dataclass(frozen=True)
class Line:
cents: int
qty: int
def __post_init__(self):
if type(self.qty) is not int or self.qty < 1:
raise ValueError("positive integer quantity")
def total(self):
return self.cents * self.qty
def total(lines):
return sum(line.total() for line in lines)
print(total([Line(125, 2), Line(40, 3)]), total([]))
try:
Line(10, 0)
except ValueError as error:
print(str(error))
Wynik
370 0 positive integer quantity
Pusty zbiór wierszy daje sumę zero.