Python 类型提示 __init__ 中的当前类

问题描述 投票:0回答:1

假设我有一节课:

class Node:
    def __init__(self, value=None, next_item=None):
        self.value: int = value
        self.next_item: Node = next_item

是否可以“输入提示”所有

__init__
参数?像这样的东西:

class Node:
    def __init__(self: Self, value: int = None, next_item: Node = None):
        self.value: int = value
        self.next_item: Node = next_item
正如我们所看到的,

next_item
无法引用
Node
,因为它还不存在。有什么办法可以做到吗?

python class oop type-hinting
1个回答
0
投票

在导入中添加行

from __future__ import annotations
,这将适用于第二个选项,但您需要删除类型注释中的
Self

© www.soinside.com 2019 - 2024. All rights reserved.