【发布时间】:2021-10-16 10:08:53
【问题描述】:
我有一个 JSON 对象,内容如下:
j = {"id": 1, "label": "x"}
我有两种类型:
class BaseModel:
def __init__(self, uuid):
self.uuid = uuid
class Entity(BaseModel):
def __init__(self, id, label):
super().__init__(id)
self.name = name
注意id 如何在BaseModel 中存储为uuid。
我可以从 JSON 对象加载Entity:
entity = Entity(**j)
我想利用 dataclass 重写我的模型:
@dataclass
class BaseModel:
uuid = str
@dataclass
class Entity:
name = str
由于我的 JSON 对象没有uuid,基于dataclass 的模型上的entity = Entitye(**j) 将抛出以下错误:
TypeError: __init__() 得到了一个意外的关键字参数 'id'
我能想到的“丑陋”的解决方案:
-
在初始化之前在 JSON 中将
id重命名为uuid:j["uuid"] = j.pop("id") -
同时定义
id和uuid:@dataclass class BaseModel: uuid = str @dataclass class Entity: id = str name = str # either use: uuid = id # or use this method def __post_init__(self): super().uuid = id
对于dataclass领域中的这种对象初始化,有没有更简洁的解决方案?
【问题讨论】:
标签: python json inheritance python-dataclasses