I want a common field for each data class, but I want to give a default value, so if I inherit it normally, this will be attached before type error. It's hard
from dataclasses import dataclass
@dataclass
class Base:
base: int = 10
@dataclass
class Extend(Base):
extend: int
type error
Also, even if you inherit a class that is not @ dataclass
, it seems that the inherited field is not inherited (to \ _ \ _ init \ _ \ _).
Write a decorator
from dataclasses import dataclass
def add(c):
@dataclass
class wrap(c):
added: int = 10
return wrap
@add
@dataclass
class DataClass:
field: str
The downside is that the interpreter is <locals> .wrap
instead of the name.
>> DataClass
<class '__main__.add.<locals>.wrap'>
Apparently the name of the class is in __qualname__
.
def add(c):
@dataclass
class wrap(c):
added: int = 10
__qualname__ = c.__qualname__
return wrap
>> DataClass
<class '__main__.DataClass'>
Recommended Posts