Signup/Sign In

Inheritance in Python Dataclass

Posted in Technology   LAST UPDATED: JUNE 24, 2023

    In this post, we will understand how dataclass behaves when they implement one of the most important object-oriented concepts: Inheritance. We have previously discussed what dataclasses are, how they behave, and their field functions. It is strongly suggested to go through those posts in detail, understand them and then jump to this topic.

    Inheritance in Python Dataclass

    What is Inheritance in Dataclass?

    I am sure all of you would be aware of Inheritance, but here is a definition:

    Inheritance is the process of adapting the features and functionalities of the parent class and using as well as improvising that inherited class in the current class according to the requirements.

    Here are a few terminologies that we will use:

    Superclass: This is also known as the base class, or the parent class, i.e. the class from which the other classes inherit features and functionalities.

    Subclass: This is also known as the child class or the class that inherits from the parent/super class.

    Dataclasses, at the end of the day, are also classes, that come with a few pre-cooked features and methods. This means inheritance behaves in the same way as it does with normal classes.

    Let us look at an example and infer a few points from it:

    from dataclasses import dataclass
    
    @dataclass
    class StudyTonight: 
        name: str
        type_of_website: str
        no_of_characters: str
    
    # class inheriting another class
    @dataclass
    class Python_StudyTonight(StudyTonight):
        name: str
        languages_covered: str

    What can we infer from the above code?

    1. We can see that both the classes that use inheritance are dataclasses. The StudyTonight class is the superclass and the Python_StudyTonight class is the subclass.

    2. One important thing to understand here is that, when the subclass inherits from the superclass, the pre-implemented __init__ method gets overridden in the subclass.

    3. The name attribute in both the subclass and superclasses is the same. It is overridden in the subclass.

    As mentioned in point 2 of the above inference, the __init__() method is overridden from superclass to subclass. Suppose __init__ method is not mentioned or improvised in the subclass (Python_StudyTonight), then the default init method needs to be provided with parameters of the superclass followed by parameters of the subclass.

    Python_StudyTonight(name: str, type_of_website: str, no_of_characters: str, languages_covered: str)

    Observe that the attribute name, even though present in both the classes, is passed as one argument to the init method. Also, the order of the parameters is such because they are passed in the order of the superclass and then the subclass.


    Below is an example of instantiating the inherited class

    from dataclasses import dataclass
    
    @dataclass
    class StudyTonight: 
        name: str
        type_of_website: str
        no_of_characters: str
    
    @dataclass
    class Python_StudyTonight(StudyTonight):
        name: str
        languages_covered: str
    new_instance = Python_StudyTonight("Studytonight",
                                       "Technical",
                                       12,
                                       "Python, C, C++")
    print(new_instance)

    Output:

    Python_StudyTonight(name='Studytonight', type_of_website='Technical', no_of_characters=12, languages_covered='Python, C, C++')
    

    The above is what happens when the init method is not explicitly specified in the subclass.

    But your next question could be, what if the init method is specifically defined in the subclass?

    In such cases, the defined init method should have the ability to initialize its class attributes as well as the superclass's attributes. Also, the order of initializing the class attributes doesn't matter.

    Below is an example demonstrating the same:

    from dataclasses import dataclass
    
    @dataclass
    
    class StudyTonight: 
        name: str
        type_of_website: str
        no_of_characters: str
    
    @dataclass(init = False)
    
    class Python_StudyTonight(StudyTonight):
        name: str
        languages_covered: str
    
        def __init__(self, type_of_website):
            self.type_of_website = type_of_website
            self.name = "Studytonight"
            self.languages_covered = "Python, C, C++"
            self.no_of_characters = 12
    
    new_instance = Python_StudyTonight("Studytonight")
    print(new_instance)

    Output:

    Python_StudyTonight(name='Studytonight', type_of_website='Studytonight', no_of_characters=12, languages_covered='Python, C, C++')


    Conclusion

    Inheritance in Python dataclasses empowers you to create robust class hierarchies, streamline code organization, and promote code reuse. By leveraging the power of inheritance, you can build upon existing dataclasses, define specialized behaviors, and ensure consistency across related classes.

    As you continue your Python programming journey, remember the flexibility and expressiveness that inheritance brings to your dataclass designs.

    Freqnelty Asked Questions(FAQs)

    1. Can I use inheritance with dataclass in Python?

    Yes, dataclass in Python fully support inheritance. You can create class hierarchies by defining child classes that inherit attributes and behaviors from parent classes, enhancing code organization, and promoting code reuse.

    2. How do I inherit from a dataclass in Python?

    Inheriting from a dataclass is similar to inheriting from a regular class. Simply define the child class using the parent class as a base, and the child class will inherit the attributes and behaviors of the parent dataclass.

    3. Can I override attributes or methods inherited from a dataclass in Python?

    Yes, you can override attributes and methods inherited from a dataclass in Python. By redefining attributes or methods in the child class, you can customize their behavior to suit the specific needs of the child class while still inheriting the rest of the parent dataclass.

    4. Can I have multiple levels of inheritance with dataclass in Python?

    Absolutely! Python allows you to create multi-level inheritance hierarchies with dataclasses. You can define a child class that inherits from another child class, which in turn inherits from a parent dataclass, enabling you to build complex class relationships.

    5. Are there any limitations or considerations when using inheritance with dataclass in Python?

    While inheritance offers great flexibility, it's important to consider the design and complexity of your class hierarchies. Be mindful of the relationships between parent and child classes, potential method name conflicts, and the overall readability and maintainability of your code. It's best to strike a balance between code reuse and keeping your class hierarchies manageable.

    Author:
    I love writing about Python and have more than 5 years of professional experience in Python development. I like sharing about various standard libraries in Python and other Python Modules.
    inheritancepython
    IF YOU LIKE IT, THEN SHARE IT

    RELATED POSTS