在__init__内部给当前类添加类型提示。

huangapple go评论133阅读模式
英文:

Type hint current class inside __init__

问题

让我们想象一下,我有一个类:

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,因为它还不存在。有没有办法做到这一点?

英文:

Let's imagine I have a class:

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

Is it possible to "type hint" all __init__ params? Something like this:

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, as we can see, can't refer to Node, because it doesn't yet exist. Are there any ways to do it?

答案1

得分: 1

在导入部分添加以下代码行:from __future__ import annotations,然后这将与第二个选项一起工作。

英文:

add line from __future__ import annotations in import and this will work with second option

huangapple
  • 本文由 发表于 2023年8月5日 00:43:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/76837798.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定