2

Is it possible to declare a default value for an attribute in a subclass in python?

Eg something like this:

@dataclass_json
@dataclass
class BaseClass:
    b: str
    a: str


@dataclass_json
@dataclass
class SubClass(BaseClass):
    c: str
    d: str
    a: str = "my value"

I tried this and I'm getting the following error:

TypeError: non-default argument 'c' follows default argument

I also tried putting a before c and d in the subclass without success (same error).

Is there a way to achieve this?

4
  • 1
    It's telling you to put a before c and d. What's confusing you about the error message? Commented Jul 7, 2021 at 5:11
  • I tried that, it throws the same error Commented Jul 7, 2021 at 5:12
  • Could you please add a plain python tag as the python-3.x tag guidance suggests? Commented Jul 7, 2021 at 6:01
  • Does this answer your question? Class inheritance in Python 3.7 dataclasses Commented Jul 7, 2021 at 6:06

1 Answer 1

3

Your derived class will have the following order of fields in __init__:

def __init__(b, a, c, d):

This is because a appears in the base class, so the base constructor is

def __init__(b, a):

To give a a default value, can give c and d default values (e.g. None):

@dataclass_json
@dataclass
class SubClass(BaseClass):
    c: str = None
    d: str = None
    a: str = "my value"
Sign up to request clarification or add additional context in comments.

4 Comments

question is a duplicate of this stackoverflow.com/questions/51575931/…
Good find. You should close it as such then
Type of c, d should be Optional[str] then
@M.Winkens. Yes

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.