英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论