我想使用@dataclass_json
装饰器来存储我的@dataclass
实例。
而且我想在实例中对一个对象有很多引用。我想保存这个引用结构(这样我就可以修改一个设置对象,并且修改将应用于许多使用这些设置的对象)。
当数据类对象位于内存中时,它可以很容易地完成,但是当我尝试将它存储在 JSON 中时,它会保存实例的副本而不是它的引用。我能以某种方式处理它吗?
PS这是我的代码示例:
from dataclasses import dataclass
from dataclasses_json import dataclass_json
from typing import List
@dataclass_json
@dataclass
class RadarSettings:
freq: float = 10e9
prf: float = 1e-3
@dataclass_json
@dataclass
class Radar:
name: str = ""
preset_settings: RadarSettings = None # Here should be references to some boilerplate preset settings for many radars
custom_settings: RadarSettings = None # And here should be the custom settings to this current radar
@dataclass_json
@dataclass
class RadarScene:
name: str = ""
radars: List["Radar"] = None
preset = RadarSettings()
radar1 = Radar(name="mega search mode radar from hell", preset_settings=preset)
radar2 = Radar(name="satanic sensor array radar", preset_settings=preset)
# The preset_settings is one same object for both radars! If I modify it, the modifications will be applied to both radars
print(id(radar1.preset_settings), id(radar2.preset_settings))
scene_to_save = RadarScene(name="Infernal scene", radars=[radar1, radar2])
loaded_scene = RadarScene.from_json(scene_to_save.to_json())
print(id(loaded_scene.radars[0]), id(loaded_scene.radars[1]))
# Alas! Here will be two instances of preset_settings saved. I need one =(