DEV Community

Divyanshu Shekhar
Divyanshu Shekhar

Posted on

1

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)
Enter fullscreen mode Exit fullscreen mode

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

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs