Open In App

Data Classes in Python | Set 4 (Inheritance)

Prerequisites: Inheritance In Python, Data Classes in Python | Set 3

In this post, we will discuss how DataClasses behave when inherited. Though they make their own constructors, DataClasses behave pretty much the same way as normal classes do when inherited.






from dataclasses import dataclass
  
  
@dataclass
class Article:
      
    title: str
    content: str
    author: str
  
  
@dataclass
class GfgArticle(Article):
      
    language: str
    author: str
    upvotes: int = 0

Few points from above code:

  1. Article is subclassed by GfgArticle
  2. Both SuperClass and SubClass are DataClasses – although super-class or sub-class being a normal class is also possible. When a DataClass inherits a normal class, the __init__() from the super-class is overridden in sub-class.
  3. author in GfgArticle overrides the same in Article – As the basic concept of inheritance, the value for its assignment is first looked in the sub-class and followed up the tree in super-class.

Behaviour of __init__() of GfgArticle:



Output:

GfgArticle(title=’DataClass’, content=’Inheritance Concepts’, author=’vibhu4agarwal’, language=’Python3′, upvotes=0)

Note:


Article Tags :