【发布时间】:2019-01-04 23:38:17
【问题描述】:
我有一个数据类对象,其中包含嵌套的数据类对象。但是,当我创建主对象时,嵌套对象变成了字典:
@dataclass
class One:
f_one: int
@dataclass
class One:
f_one: int
f_two: str
@dataclass
class Two:
f_three: str
f_four: One
data = {'f_three': 'three', 'f_four': {'f_one': 1, 'f_two': 'two'}}
two = Two(**data)
two
Two(f_three='three', f_four={'f_one': 1, 'f_two': 'two'})
obj = {'f_three': 'three', 'f_four': One(**{'f_one': 1, 'f_two': 'two'})}
two_2 = Two(**data)
two_2
Two(f_three='three', f_four={'f_one': 1, 'f_two': 'two'})
如您所见,我尝试将所有数据作为字典传递,但没有得到预期的结果。然后我尝试先构造嵌套对象并通过对象构造函数传递,但得到了相同的结果。
理想情况下,我想构造我的对象以获得类似的东西:
Two(f_three='three', f_four=One(f_one=1, f_two='two'))
除了在访问对象属性时手动将嵌套字典转换为相应的数据类对象之外,还有其他方法可以实现吗?
提前致谢。
【问题讨论】:
-
如果您实际使用
obj,您的第二种方法就可以了。Two(**obj)给我Two(f_three='three', f_four=One(f_one=1, f_two='two')) -
感谢您指出我的错误。知道是否可以使用第一种方法实现相同的结果?如果您的数据类对象中有多个嵌套对象,则第二种方法似乎太乏味了。
标签: python object serialization nested python-dataclasses