我有一個這樣的資料類:
class chapter:
title: str
text: str = ''
chapter: List['chapter'] = field(default_factory=list)
removed: bool = False
假設有一個串列物件,其中包含具有這些值的該資料類的實體:
content = [
chapter(
'chapter 1',
chapter=[
chapter('subchapter 1', "Lorem ipsum dolor"),
chapter('subchapter 2', "Nullam a ligula")
]
),
chapter(
'chapter 2',
chapter=[
chapter('subchapter 1', "Fusce eget commodo augue"),
chapter('subchapter 2', "Pellentesque pretium")
]
),
chapter(
'chapter 3', removed=True
),
chapter(
'chapter 3',
chapter=[
chapter('subchapter 1', "Duis sit amet tempus lectus"),
]
),
]
假設我想將removed索引為 0 的選定章節以及該章節的所有子章節中的值遞回設定為 True。我怎樣才能做到這一點?任何建議表示贊賞。
uj5u.com熱心網友回復:
您的代碼中的命名有點混亂 - 您應該命名類Chapter而不是應該呼叫chapter串列。chapterchapters
話雖如此,這似乎是您想要的:
from typing import List
from dataclasses import dataclass, field
@dataclass
class Chapter:
title: str
text: str = ''
chapters: List['Chapter'] = field(default_factory=list)
removed: bool = False
def remove(self):
self.removed = True
for chapter in self.chapters:
chapter.remove()
content = [
Chapter(
title='chapter 1',
chapters=[
Chapter('subchapter 1', "Lorem ipsum dolor"),
Chapter('subchapter 2', "Nullam a ligula")
]
),
Chapter(
'chapter 2',
chapters=[
Chapter('subchapter 1', "Fusce eget commodo augue"),
Chapter('subchapter 2', "Pellentesque pretium")
]
),
Chapter(
'chapter 3', removed=True
),
Chapter(
'chapter 3',
chapters=[
Chapter('subchapter 1', "Duis sit amet tempus lectus"),
]
),
]
content[0].remove()
print(content)
呼叫.remove()一章設定.removed為True,但也呼叫.remove()其任何子章,遞回地設定.removed所有這些子章及其子章。
uj5u.com熱心網友回復:
使用遞回函式:
def remove_recursive(chapter_instance: chapter) -> None:
chapter_instance.removed = True
for c in chapter_instance.chapter:
remove_recursive(c)
請注意,通常您會呼叫您的 class Chapter,然后可以使用該名稱chapter來參考該類的實體(而不是chapter_instance像我在這里非常尷尬地所做的那樣。)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/515670.html
