Python实现带自类型子项层级结构的Page类的问题咨询
Python实现带自类型子项层级结构的Page类的问题咨询
嘿,我来帮你梳理下这两个问题,顺便给你一些实用的优化建议~
首先先解释你遇到的TypeError:你当前把self.children赋值成了list[Page]这个类型对象,而不是一个实际的列表实例,所以调用append时才会报错——append是列表实例的方法,不是类型本身的方法,这是核心问题。
问题1:children属性的正确写法
你需要把它初始化为空列表,同时加上正确的类型注解,根据Python版本不同有两种写法:
- Python 3.9及以上(支持标准库泛型类型):
直接在属性上标注类型并初始化空列表:self.children: list[Page] = [] - Python 3.8及以下:
需要先从typing模块导入List,再做标注:from typing import List # ... self.children: List[Page] = []
问题2:add_child方法的类型提示解决
在类定义内部直接写child: Page会报错,是因为Python解释器还没完全完成Page类的定义,找不到这个名字。有三种解决方式:
- 用字符串字面量代替类名(兼容所有Python版本):
def add_child(self, child: 'Page'): self.children.append(child) - Python 3.11+使用Self类型(更优雅的写法):
先从typing导入Self,再用它做类型提示:from typing import Self # ... def add_child(self, child: Self): self.children.append(child) - 导入
from __future__ import annotations(推荐多版本兼容场景):
在文件最顶部添加这句,它会让所有类型注解以字符串形式存储,延迟到运行时再解析,这样就能直接写child: Page了:from __future__ import annotations
完整修正后的示例代码(Python 3.9+)
from __future__ import annotations class Page: def __init__(self, id: int, title: str): self.id = id self.title = title self.children: list[Page] = [] # 正确初始化+类型标注 def add_child(self, child: Page): self.children.append(child)
额外优化建议
- 加个
__repr__方法,方便调试时查看对象信息:def __repr__(self): return f"Page(id={self.id}, title='{self.title}', children_count={len(self.children)})" - 写个递归方法遍历所有后代节点:
def get_all_descendants(self): descendants = [] for child in self.children: descendants.append(child) descendants.extend(child.get_all_descendants()) return descendants - 增加根据ID递归查找节点的方法:
def find_by_id(self, target_id: int) -> Page | None: if self.id == target_id: return self for child in self.children: result = child.find_by_id(target_id) if result is not None: return result return None
备注:内容来源于stack exchange,提问作者HanSooloo
相关产品推荐
相关产品推荐

