#πŸ”’ Inheritance that involves overwriting parent attribute in dataclass

7 messages Β· Page 1 of 1 (latest)

cyan lily
#

Hi,

I'm trying to overwrite a required attributed of the parent class using a default value in the subclass, but it looks like dataclass is ignoring it.

Here is an example where I attempt to overwrite a in the parent class:

from dataclasses import dataclass

@dataclass(kw_only=True)
class Parent:
    a: str # Required field to be populated by subclass
    b: float
    c: bool = False

@dataclass(kw_only=True)
class Subclass(Parent):
    a = 'bob'

x = Subclass(b=3.14)

Error produced

TypeError: Subclass.__init__() missing 1 required keyword-only argument: 'a'

It would be ideal if I could do this without involving __init__(...) or __post_init__(...) in the subclass as the actual use case has a lot more parameters, some of them nested objects.

hallow bronzeBOT
#

@cyan lily

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

cyan lily
#

🀯

cyan lily
hallow bronzeBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.