Data Classes in Python | Set 5 (post-init)
Prerequisite: Data Classes in Python | Set 4
In this post, we will discuss how to modify values of some attributes during object creation without coding it in __init__() by using post-init processing.
__post_init__(): This function when made, is called by in-built __init__() after initialization of all the attributes of DataClass. Basically, object creation of DataClass starts with __init__() (constructor-calling) and ends with __post__init__() (post-init processing).
Use –
This feature is very handy at times when certain attributes are dependent on the parameters passed in the __init__() but do not get their values directly from them. That is, they get their values after performing some operation on a subset of arguments received in the constructor.
Continuing the same example we’ve been seeing in this series of articles, suppose there is an attribute called author_name which gets its value from the profile handle to name mapping in the defined dictionary name.
So author_name is dependent on profile handle which author attribute receives, so using __post_init__() should be an ideal choice this case.
from dataclasses import dataclass, field name = {'vibhu4agarwal': 'Vibhu Agarwal'} @dataclassclass GfgArticle: title : str language: str author: str author_name: str = field(init = False) upvotes: int = 0 def __post_init__(self): self.author_name = name[self.author] dClassObj = GfgArticle("DataClass", "Python3", "vibhu4agarwal") print(dClassObj) |
Output:
GfgArticle(title=’DataClass’, language=’Python3′, author=’vibhu4agarwal’, author_name=’Vibhu Agarwal’, upvotes=0)
Can default_factory be an alternative?
No, because default_factory accepts zero argument function or callable, so it can’t receive any arguments and return a value after performing some operations on them.
Recommended Posts:
- Data Classes in Python | Set 4 (Inheritance)
- Data Classes in Python | An Introduction
- Data Classes in Python | Set 2 (Decorator Parameters)
- Data Classes in Python | Set 6 (interconversion to and from other datatypes)
- Data Classes in Python | Set 3 (dataclass fields)
- Abstract Classes in Python
- Python for Data Science
- Data Analysis and Visualization with Python | Set 2
- Inbuilt Data Structures in Python
- Working With JSON Data in Python
- Data analysis and Visualization with Python
- Exploratory Data Analysis in Python | Set 1
- Exploratory Data Analysis in Python | Set 2
- Python IDEs For Data Science
- Data visualization with different Charts in Python
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



