Python Data Class Inheritance With Example
September 24, 2020 / By HTD / Python / Data Classes, Inheritance
Advertisement
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 the 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.
@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.
@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.
Python Data Class Object Creation
In python data class inheritance, the child class has to be provided with the parent class parameters too.
student = Student('HTD School', 'Delhi', 'Arpit', 10, 17, [98, 85, 90])
>>> print(student)
Student(school_name='HTD School', address='Delhi', name='Arpit', clss=10, stu_id=17, marks=[98, 85, 90], avg_marks=91.0)
In the above code, we see the Student class object creation takes 6 positional arguments, but the student class has only 4 fields.
This happens because the student class inherits the School class and thus the school class fields have to be provided in the student class.
Field Resolution Order in Python
It is possible that the parent and the child class have the property with the same name. What will happen in that case?
Example:
@dataclass
class School():
name: str = 'HTD School'
address: str = 'Delhi'
@dataclass()
class Student(School):
name: str = 'HTD'
clss: int = 10
stu_id: int = 17
student = Student()
As you can see, there is a name property in both the classes and the default values are set. As the student name field occurs at last it will override the school name field.
Output:
>>> print(student)
Student(name='HTD', address='Delhi', clss=10, stu_id=17)
Hope you like it!
Learn More:
Learn more about Python Data Class from the official Documentation.