CKTIS / Python
dataclass.__post_init__
Le traitement après initialisation calcule les champs dépendants après les affectations de l’initialiseur généré.
Version : Python 3.14; repository image, production runtime not attested
Syntaxe
def __post_init__(self, multiplier): ...Le traitement après initialisation calcule les champs dépendants après les affectations de l’initialiseur généré.
dataclass.__post_init__
Ce libellé appartient au catalogue. La fonction décoratrice dataclass ne possède pas cet attribut. Le __init__ généré appelle self.__post_init__ avec les valeurs InitVar dans l’ordre déclaré. Un initialiseur personnalisé doit l’appeler explicitement si nécessaire.
multiplier sert uniquement à l’initialisation. Avec 6 et 4, total vaut 24.
from dataclasses import dataclass
events=[]
@dataclass
class Custom:
def __init__(self): events.append('own')
def __post_init__(self): events.append('post')
Custom()
assert events==['own']
Exemples
from dataclasses import InitVar, dataclass, field
@dataclass
class Price:
cents: int
multiplier: InitVar[int]
total: int = field(init=False)
def __post_init__(self, multiplier):
if multiplier < 0:
raise ValueError("negative")
self.total = self.cents * multiplier
p = Price(6, 4)
print(p.total, hasattr(p, "multiplier"))
Résultat
24 False
multiplier sert uniquement à l’initialisation. Avec 6 et 4, total vaut 24.