Python 3 打字标注与亲子设计

Python 3 typing annotation and parent-child design

我正在编写一些 Python 代码,其中我必须使用这样的父子设计:

from typing import List


class Parent(object):

    def add_children(self, child: List[Child]):
        """Do something here"""


class Child(object):

    def set_parent(self, parent: Parent):
        """Do something here"""

但是 Python 提出 NameError 并抱怨 Child class 没有定义。这是合乎逻辑的,因为它在 Parent class.

在 C++ 中是否有类似 "Forward declaration" 的方法来处理此类问题,或者是否有其他方法?我尝试 Google 但没有成功。

您可以使用字符串指定名称:

def add_children(self, child: "List[Child]"):

如需进一步说明,请查看

这是一个循环依赖问题。

当你的代码是运行遇到Parentclass时,它会寻找Childclass的定义,但是是在后面定义的所以它找不到它并抛出错误!

如果你交换这两个定义,当你的代码是 运行 并且遇到 Child class 时,它会寻找 Parent class定义,但它是在之后定义的,所以找不到它并抛出错误!

要解决此问题,您必须在 中标识的名称中使用字符串,问题将得到解决

 def add_children(self, child: "List[Child]"):