小编Rom*_*ode的帖子

使用自引用类型提示创建递归数据类

我想用 Python 编写数据类定义,但无法在声明中引用同一类。

我主要想要实现的是这个嵌套结构的类型,如下图所示:

 @dataclass
 class Category:
     title: str
     children: [Category] # I can't refer to a "Category"
  
 tree = Category(title='title 1', children=[
     Category('title 11', children=[]),
     Category('title 12', children=[])
 ])
Run Code Online (Sandbox Code Playgroud)

python type-hinting recursive-datastructures python-dataclasses

25
推荐指数
1
解决办法
7088
查看次数