【问题标题】:Recursive class typing in python [duplicate]python中的递归类键入[重复]
【发布时间】:2021-01-26 21:02:40
【问题描述】:

我正在寻找一个带有递归字段的类

我尝试以下代码:

class Heh:
  child_hehs: list[Heh]

但我得到以下错误

NameError: name 'Heh' 未定义

所以我尝试另一个代码:

class MetaHeh(Heh):
  pass

class Heh:
  child_hehs: list[MetaHeh]

我又遇到了以下错误:

NameError: name 'Heh' 未定义

我怎样才能通过打字来实现这个代码?

【问题讨论】:

标签: python typing


【解决方案1】:

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

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__ 导入)。

【讨论】:

  • 也可以使用注解:from __future__ import annotationsclass Heh: child_hehs: list[Heh]
  • 不错的功能:-)
猜你喜欢
  • 2016-11-15
  • 2023-01-30
  • 2016-05-06
  • 2023-04-11
  • 2020-10-14
  • 2019-11-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多