[英]What is the python equivalent of setting instances of a class within the __init__() method?
I'd like to send in a list of dependencies
as part of creating a DAGNode
: what is the supported way to achieve a similar behavior in python - given it seems this exact syntax were not supported?作为创建
DAGNode
的一部分,我想发送dependencies
项列表:在 python 中实现类似行为的受支持方式是什么 - 假设似乎不支持这种确切的语法?
from typing import TypeVar, Generic
T = TypeVar('T')
class DAGNode(Generic[T]):
# Apparently the `DAGNode` type does not exist yet so this fails
def __init__(self, id: T, dependencies: set[DAGNode[T]]):
self.id = id
self.dependencies = dependencies
Since the class does not exist yet you have to reference it including its name between single quote like this由于 class 尚不存在,因此您必须像这样在单引号之间引用它,包括它的名称
from typing import TypeVar, Generic, Set
T = TypeVar('T')
class DAGNode(Generic[T]):
# Apparently the DAGNode type does not exist yet so this fails
def __init__(self, type_id: T, dependencies: Set['DAGNode[T]']):
self.id = type_id
self.dependencies = dependencies
Notice I used type_id
instead of id to not shadow the builtin function id
请注意,我使用
type_id
而不是 id 来避免隐藏内置 function id
In Python 3.7 and later, you can add the line在 Python 3.7 及更高版本中,您可以添加以下行
from __future__ import annotations
near the beginning of the code.靠近代码的开头。 Annotations aren't evaluated then anymore automatically (only valid expression syntax is checked).
然后不再自动评估注释(仅检查有效的表达式语法)。
For more details see https://peps.python.org/pep-0563/有关详细信息,请参阅https://peps.python.org/pep-0563/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.