CKTIS / Python
dataclass.__post_init__
Metoda instancji po inicjalizacji pozwala wyliczyć pola zależne po przypisaniach wygenerowanego konstruktora.
Wersja: Python 3.14; repository image, production runtime not attested
Składnia
def __post_init__(self, multiplier): ...Metoda instancji po inicjalizacji pozwala wyliczyć pola zależne po przypisaniach wygenerowanego konstruktora.
dataclass.__post_init__
To etykieta katalogowa. Funkcja dekorująca dataclass nie ma tego atrybutu. Wygenerowany __init__ wywołuje self.__post_init__ z wartościami InitVar w kolejności deklaracji. Przy własnym konstruktorze trzeba wywołać metodę samodzielnie.
Argument multiplier nie jest polem instancji. Z 6 i 4 powstaje total równe 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']
Przykłady
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"))
Wynik
24 False
Argument multiplier nie jest polem instancji. Z 6 i 4 powstaje total równe 24.