如何将参数传递给嵌套@dataclass

How to pass parameters to nestting @dataclass

我得到了 2 条数据 类。我想将参数传递给一并能够在二上获取它。

@dataclass
class One:

    id: int = 0
    text: str = "New York"
    a: str = ""
    b: str = ""

    def __post_init__(self):
        self.params = [self.a, Two(name=self.b)]
    params: List = field(default_factory=list)


@dataclass
class Two:
    home: List = field(default_factory=list)
    name: str = ""

不知何故 -> One(a = "test1", b = "text2")

我想要得到的结果:

{
   "id":0,
   "text":"abc",
   "params":[
      "test1",
      {
         "home":[],
         "name":"text2"
      }
   ]
}

使用InitVar仅将一个字段标记为“init-only”,它被传递给__post_init__而不存储为常规字段

from dataclasses import dataclass, field, InitVar, asdict


@dataclass
class Two:
    home: list = field(default_factory=list)
    name: str = ""


@dataclass
class One:

    id: int = 0
    text: str = "New York"
    params: list = field(default_factory=list)

    a: InitVar[str] = ""
    b: InitVar[str] = ""

    def __post_init__(self, a, b):
        self.params = [a, Two(name=b)]


print(asdict(One(a="test1", b="text2")))
# {'id': 0, 'text': 'New York', 'params': ['test1', {'home': [], 'name': 'text2'}]}