【问题标题】:Type annotations for a class with attributes of the same type?具有相同类型属性的类的类型注释?
【发布时间】:2020-08-27 15:34:21
【问题描述】:

我有 Node 类,Node 类有 2 个孩子,孩子 A 和 B,但它们是具有相同结构的同一个类,因为孩子可以有自己的孩子。

代码是python,语言不让我下一个,标记我一个错误:

class Node:
    a: Node
    b: Node
    name: str
    value: int

有没有办法做到这一点,对象本身是嵌套的?

我的问候

【问题讨论】:

  • 感谢@martineau,我删除了屏幕截图并编写了代码。看起来更好,帖子看起来更好。

标签: python python-3.x oop type-annotation


【解决方案1】:

根据How do I specify that the return type of a method is the same as the class itself?,最简单的解决方案是使用带有类名的字符串:

a : 'Node'

【讨论】:

  • 您回答了一个您投票结束的问题似乎很奇怪。
猜你喜欢
  • 2021-07-24
  • 2017-04-04
  • 2013-03-28
  • 1970-01-01
  • 1970-01-01
  • 2020-10-03
  • 1970-01-01
  • 1970-01-01
  • 2013-09-17
相关资源
最近更新 更多