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

如何在Python中递归设置嵌套dataclass的removed属性为True

递归设置章节及其子章节的removed属性为True的实现方法

你可以通过递归函数实现需求:先将目标章节的removed设为True,再遍历其所有子章节,对每个子章节重复该操作,直到所有层级的子章节都被处理。

实现代码

def mark_removed(chap: chapter) -> None:
    # 设置当前章节的removed为True
    chap.removed = True
    # 递归处理所有子章节
    for sub_chapter in chap.chapter:
        mark_removed(sub_chapter)

# 调用函数处理content中索引为0的章节
if content:  # 先确保content不为空,避免索引越界
    mark_removed(content[0])

逻辑说明

  1. 函数mark_removed接收一个chapter实例作为参数,首先直接修改它的removed属性为True。
  2. 接着遍历该章节的chapter列表(所有子章节),对每个子章节递归调用mark_removed函数,逐层处理所有嵌套的子章节。
  3. 最后调用时传入content[0],即可将根章节及其所有后代子章节的removed属性全部设为True。

验证示例

可以通过以下代码验证结果:

# 打印content[0]及其子章节的removed状态
def print_removed_status(chap: chapter, indent: int = 0):
    print(f"{'    '*indent}{chap.title}: removed={chap.removed}")
    for sub_chap in chap.chapter:
        print_removed_status(sub_chap, indent + 1)

print_removed_status(content[0])

输出会显示:

chapter 1: removed=True
    subchapter 1: removed=True
    subchapter 2: removed=True

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 18:01:05