递归 class 输入 python

Recursive class typing in python

我正在寻找带有递归字段

的class

我试试下面的代码:

class Heh:
  child_hehs: list[Heh]

但我得到以下错误

NameError: name 'Heh' is not defined

所以我尝试另一个代码:

class MetaHeh(Heh):
  pass

class Heh:
  child_hehs: list[MetaHeh]

我又遇到了以下错误:

NameError: name 'Heh' is not defined

我如何通过键入来实现此代码?

在其声明中使用递归类型的名称。例如:

class Heh:
  child_hehs: list['Heh']

如果你可以使用 python 3.7.0b1 及更高版本你可以使用 Postponed Evaluation of Annotations.

from __future__ import annotations 
class Heh:     
    child_hehs: list[Heh]

此功能有望成为 python 3.10 语言的一部分(换句话说,无需 __future__ 导入)。