[Python] Inheritance with dataclasses

Discussão em 'Python' iniciado por Stack, Março 17, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to understand what are the good practices when using inheritance with dataclasses. Let's say I want an "abstract" parent class containing a set of variables and methods, and then a series of child classes that inherit these methods and the variables, where in each of them the variables have a different default value.

    from dataclasses import dataclass


    @dataclass
    class ParentClass:
    a_variable: str

    def a_function(self) -> None:
    print("I am a class")

    # ONE
    @dataclass
    class DataclassChild1(ParentClass):
    a_variable: str = "DataclassChild"

    # TWO
    @dataclass
    class DataclassChild2(ParentClass):
    def __init__(self) -> None:
    super().__init__(a_variable="Child")

    # THREE
    class ClassChild(ParentClass):
    def __init__(self) -> None:
    super().__init__(a_variable="Child")


    What would be the correct way to implement this (one/two/three), if any? Or is it an overkill and it would be best to just use different instances of ParentClass, passing different values to the constructor?

    I think I should use the @dataclass decorator also for the child classes, but if I check the type of the child class, that seems to be a dataclass even if I don't use it.

    Plus, I feel like overwriting __init__ defeats the purpose of using a dataclass in the first place, but on the other hand the standard dataclass syntax seems useless because it would mean having to rewrite all the variables in the child classes (a_variable: str = "DataclassChild").

    Continue reading...

Compartilhe esta Página