Post-Init Processing In Python Data Class
September 23, 2020 / By / /
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
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.
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.
def __post_init__(self): self.avg_marks = sum(self.marks) / len(self.marks)
In the __post_init__ function in python Data Class, the avg_marks is set by adding all the marks and dividing it by the total length of the list.
Hope You Like It!
Learn more about Post-Init Processing in Python Data Class from the official Documentation.
In the next blog, we will learn about Inheritance in Python Data Class.