Post-Init Processing In Python Data Class
In the previous blog, we learned about Fields in Python Data Classes. This time we are going to learn about post-init processing in python data class.
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 has been assigned.
This can be done by 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.
post-init function in python
from dataclasses import dataclass, field
@dataclass()
class Student():
name: str
clss: int
stu_id: int
marks: []
avg_marks: float = field(init=False)
def __post_init__(self):
self.avg_marks = sum(self.marks) / len(self.marks)
student = Student('HTD', 10, 17, [98, 85, 90])
print(student)
Student(name='HTD', clss=10, stu_id=17, marks=[98, 85, 90], avg_marks=91.0)
To achieve this functionality you will also need to implement the field and set the init parameter as false to the variable which you want to set in the post-init function.
When the field init parameter is set to false for a variable we don’t need to provide value for it while the object creation.
If you are confused about what are fields in python data class and how to set the field parameters read the previous blog on the python data class fields and learn how they can be used to optimize the python class.
Learn more from:
https://hackthedeveloper.com/python-post-init-data-class/