You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让类中作为超集的字典与子集字典保持同步?

问题:实现支持多类型节点同步访问的类

我想创建一个包含节点字典的类,节点分为points、vertices等多种类型,要求能高效遍历或访问所有节点、仅points节点或仅vertices节点。

最初的类结构如下:

class A:
   _nodes: dict
   _points: dict
   _vertices: dict

但显然修改_points不会同步到_nodes,反之亦然。

我的第一个想法是使用数据描述符来保持三者同步,但不知道具体如何实现,这种方案是否可行?

我也考虑将_nodes实现为嵌套字典,通过property返回子集:

class A:
   _nodes = {"points": dict(), "vertices": dict()}
   @property
   def _points(self):
        return(self._nodes["points"])
   @property
   def _vertices(self):
        return(self._nodes["vertices"])

但担心每次访问points或vertices时,哈希计算和额外的字典查找会带来性能开销。

理想情况下,我希望为nodes、points和vertices提供带缓存的公共属性视图,并通过数据描述符更新:

class NodeDescriptor():
    def __set__(self, obj, value):
        od = obj.__dict__
        od["_nodes"] = value
        if "nodes" in od: del od["nodes"]

 class PointDescriptor(): ...
 class VertexDescriptor(): ...

class A:
   _nodes = NodeDescriptor()
   _points = PointDescriptor()
   _vertices = VertexDescriptor()

   @cached_property
   def nodes(self): return NodeView(self._nodes)
   @cached_property
   def points(self): return NodeView(self._points)
   @cached_property
   def vertices(self): return NodeView(self._vertices)

但这种方案中,将_nodes设为嵌套字典的思路不可行,因为修改nodes["vertex"] = new_dict()时无法触发描述符。


内容的提问来源于stack exchange,提问作者Jaka Belec

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 06:47:14