繁体   English   中英

在 __init__() 方法中设置 class 实例的 python 是什么?

[英]What is the python equivalent of setting instances of a class within the __init__() method?

作为创建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

由于 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

请注意,我使用type_id而不是 id 来避免隐藏内置 function id

在 Python 3.7 及更高版本中,您可以添加以下行

from __future__ import annotations

靠近代码的开头。 然后不再自动评估注释(仅检查有效的表达式语法)。

有关详细信息,请参阅https://peps.python.org/pep-0563/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM