Home > Blockchain >  Are the children of Python data classes always data classes themselves?
Are the children of Python data classes always data classes themselves?

Time:08-24

Suppose I create a parent class and a child class in Python like so:

@dataclass
class MyParent:
    an_attribute: str = "Hello!"
    another_attribute: str = "Dave!"

@dataclass
class MyChild(MyParent):
    another_attribute: str = "Steve!"

Then, clearly, both MyParent and MyChild will be data classes.

But, what happens if I use the following syntax to create MyChild instead?

class MyChild(MyParent):
    another_attribute: str = "Steve!"

Testing on my own machine suggests that, even with the latter syntax, MyChild will also be a data class. But are the children of data classes always data classes themselves? Are there any pitfalls to the latter approach? Is the @dataclass decorator essentially redundant in the definition of the child?

CodePudding user response:

Adding the decorator again is required. Without it, the fields of the child class are not created properly.

>>> @dataclass
... class MyParent:
...     an_attribute: str = "Hello!"
...     another_attribute: str = "Dave!"
... 
... class MyChild(MyParent):
...     another_attribute: str = "Steve!"
... 
>>> MyChild().another_attribute  # returns the incorrect default
'Dave!'

CodePudding user response:

The dataclass magic is not triggered for the non-dataclass version of My_Child, although it will inherit the special dataclass attributes (__dataclass_fields__ etc) from My_Parent, but only for the parent's attributes

Try this:

class MyChild(MyParent):
    another_attribute: str = "Steve!"
    yet_another_attribute : str = "Mickey!"

You will see that yet_another_attribute is a class member, not an instance one

  • Related