Python嵌套Dataclass缺失字段自动生成默认值问题咨询
解决嵌套Dataclass字段缺失时的默认值生成问题
问题原因
当data_key_missing中没有f_four键时,data.get("f_four")返回None,而One类的__init__方法会调用传入参数的get方法,None没有该方法,因此抛出AttributeError。
修正方案
在获取f_four数据时,给get方法设置默认空字典,确保即使键缺失,也能传入One类可处理的对象;同时修正One类中类型注解的不一致问题(原代码f_one定义为Optional[int],但__init__里写成了Optional[str])。
修正后的完整代码
from dataclasses import dataclass, field from typing import Optional @dataclass class One: f_one: Optional[int] = field(default=None) f_two: Optional[str] = field(default=None) def __init__(self, data): # 修正类型注解,与类定义保持一致 self.f_one: Optional[int] = data.get("f_one", None) self.f_two: Optional[str] = data.get("f_two", None) @dataclass class Two: f_three: str f_four: Optional[One] def __init__(self, data): self.f_three: str = data.get("f_three") # 添加默认空字典,处理f_four键缺失的情况 self.f_four: Optional[One] = One(data.get("f_four", {})) data_nested_fields_missing = {'f_three': 'three', 'f_four':{}} # 返回 Two(f_three='three', f_four=One(f_one=None, f_two=None)) data_one_field = {'f_three': 'three', 'f_four':{'f_one': 1}} # 返回 Two(f_three='three', f_four=One(f_one=1, f_two=None)) data_key_missing = {'f_three': 'three'} # 现在返回 Two(f_three='three', f_four=One(f_one=None, f_two=None)) print(Two(data_nested_fields_missing)) print(Two(data_one_field)) print(Two(data_key_missing))
其他可选写法
如果需要更明确的空值判断,也可以先取出数据再处理:
def __init__(self, data): self.f_three: str = data.get("f_three") f_four_data = data.get("f_four") # 若数据为None,替换为空字典 if f_four_data is None: f_four_data = {} self.f_four: Optional[One] = One(f_four_data)
内容的提问来源于stack exchange,提问作者Diana Kerrala
相关产品推荐
相关产品推荐

