通过键入引用此自定义 class

Referencing this custom class with typing

我想使用类型提示为链表定义一个节点。一个 Node 实例需要引用另一个 Node 实例,所以我想在 __init__.

中接受类型为 Node 的可选参数

我试过这个:

from typing import Optional

class Node:
    def __init__(self, value: int, next: Optional[Node] = None):
        pass

我收到一个错误:Node is not defined 来自 Optional[Node]

查看 。您可以:

  1. 在文件顶部使用 from __future__ import annotations,然后像您一样使用 Node
  2. 使用字符串 ('Node'),请参阅@Diptangsu Goswami 的评论。
  3. 从 Python 3.11 开始(尚未发布)您将可以使用 from typing import Self 然后 Optional[Self].