1

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?

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
Tom
  • 2,545
  • 5
  • 31
  • 71

1 Answers1

2

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"
Mad Physicist
  • 107,652
  • 25
  • 181
  • 264