In the previous example, sally’s age was a non-positive integer and zachary’s age was a float value. To resolve erroneous input, a __post_init__ method can be used:
1
2
3
4
5
6
7
8
9
10
11
12
13
fromdataclassesimportdataclass@dataclassclassPerson:first_name:strlast_name:strage:intdef__post_init__(self):ifnotisinstance(self.age,int):raiseValueError("age is not an int")ifself.age<=0:raiseValueError("age must be a positive integer greater than 0")
sally’s error:
1
ValueError: age must be a positive integer greater than 0