Can Dataclasses inherit from other Dataclasses? How are fields ordered in the generated __init__?

Python interview question for Advanced practice.

Answer

Yes, inheritance is fully supported. Ordering: Python traverses the MRO in reverse order (from base to child). Fields from the base class come first in the generated init argument list, followed by fields from the child class. Constraint: If Base has a field with a default value (x: int = 0), then all fields in Child must also have default values. Otherwise, the init signature would have a non-default argument following a default argument (def init(self, x=0, y)), which is a SyntaxError.

Explanation

If a base class has a field with a default value, the subclass cannot add a field without a default value, due to Python's argument ordering rules.

Related Questions