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

如何用类枚举结构定义可链式访问的常量字符串树?

实现静态字符串常量树的方案

要实现你描述的静态字符串常量树,让链式访问返回完整路径字符串,核心思路是用自定义类封装每个节点——原生字符串无法附加子属性,而自定义类既可以保存节点名称和完整路径,又能定义子节点属性。

以下是具体实现:

class PathNode:
    def __init__(self, parent_path: str, node_name: str):
        # 节点自身的名称
        self.name = node_name
        # 拼接完整路径
        self.full_path = f"{parent_path}.{node_name}" if parent_path else node_name

    # 直接打印或在字符串上下文使用时返回完整路径
    def __str__(self) -> str:
        return self.full_path

    # 交互式环境下显示完整路径
    def __repr__(self) -> str:
        return self.full_path

# 构建静态结构
# 根节点
structure = PathNode("", "structure")
# 根节点的子节点
structure.house = PathNode(structure.full_path, "house")
structure.tower = PathNode(structure.full_path, "tower")
# house节点的子节点
structure.house.green_house = PathNode(structure.house.full_path, "green_house")
structure.house.yellow_house = PathNode(structure.house.full_path, "yellow_house")
# tower节点的子节点
structure.tower.small_tower = PathNode(structure.tower.full_path, "small_tower")
structure.tower.big_tower = PathNode(structure.tower.full_path, "big_tower")

使用方式

  • 获取节点自身名称:structure.house.name → 返回'house'
  • 获取完整路径:直接打印或转换为字符串即可
    print(structure.house.yellow_house)  # 输出: structure.house.yellow_house
    path = str(structure.tower.small_tower)  # path的值为 'structure.tower.small_tower'
    

进阶优化(更简洁的定义)

如果觉得手动创建子节点繁琐,可以用类封装层级结构,让代码更清晰:

class PathNode:
    def __init__(self, full_path: str, node_name: str):
        self.name = node_name
        self.full_path = full_path

    def __str__(self):
        return self.full_path

    def __repr__(self):
        return self.full_path

class Structure(PathNode):
    def __init__(self):
        super().__init__("structure", "structure")
        self.house = House(f"{self.full_path}.house")
        self.tower = Tower(f"{self.full_path}.tower")

class House(PathNode):
    def __init__(self, full_path: str):
        super().__init__(full_path, "house")
        self.green_house = PathNode(f"{self.full_path}.green_house", "green_house")
        self.yellow_house = PathNode(f"{self.full_path}.yellow_house", "yellow_house")

class Tower(PathNode):
    def __init__(self, full_path: str):
        super().__init__(full_path, "tower")
        self.small_tower = PathNode(f"{self.full_path}.small_tower", "small_tower")
        self.big_tower = PathNode(f"{self.full_path}.big_tower", "big_tower")

# 初始化根节点
structure = Structure()

这种方式把每个层级的结构封装到单独类中,更符合静态结构的定义习惯,维护起来更方便。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 17:11:16