Let’s first understand the problem.
Python Data Classes
Python Data Class
from dataclasses import dataclass
@dataclass()
class Student():
name: str
clss: int
stu_id: int
marks: []
avg_marks: float
student = Student('HTD', 10, 17, [11, 12, 14], 50.0)
>>> print(student)
Student(name='HTD', clss=10, stu_id=17, marks=[11, 12, 14], avg_marks=50.0)
The above code is a simple python data class example. The data fields of the class are initiated from the init function.
In this example, we are initiating the value of the avg_marks while initiating the object, but we want to get the average of the marks after the marks have been assigned.
This can be done by the post_init function in python.
Post-Init Processing In Python Data Class
The post-init function is an in-built function in python and helps us to initialize a variable outside the init function.
Learn more from the original post: Python Post-Init Processing Data Class
Top comments (0)