Python Data Class Inheritance With Example

in python •  4 years ago 

In the previous blog, we learned about Post-Init Processing in Python Data Class. This time we will learn how about Inheritance in Python Data Class.

Prerequisite
Before learning inheritance in the python data class, you should know the basics of python data class and why we need it?

Also learn the Parameters that python data class takes and the field parameters of the class properties.

Parent Data Class
We will carry forward the previous example and create a parent class for our student class i.e the school class. The Parent School class takes only fields, the school name, and the address.

Parent Data Class
@dataclass
class School():
school_name: str
address: str
Python Data Class Inheritance
Inheriting a data class to another is the same as we do in Object-Oriented Programming. Just provide the parent class name to the child class parenthesis.

Inheritance in python Data Class
@dataclass()
class Student(School):
name: str
clss: int
stu_id: int
marks: list
avg_marks: float = field(init=False)

def __post_init__(self):
    self.avg_marks = sum(self.marks) / len(self.marks)

If you are not understanding what the post_init methods do? Read the previous blog on the Python Data Class Post-Init Processing.
Read more from :
https://hackthedeveloper.com/python-data-class-inheritance/

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!