首页 > 解决方案 > Python 3 打字注解和父子设计

问题描述

我正在编写一些 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 提出了 aNameError并抱怨Child该类没有定义。这是合乎逻辑的,因为它在Parent类之下。

C++ 中是否有类似“前向声明”的东西来处理这样的问题,还是有其他方法?我试图谷歌它没有成功。

标签: pythonparent-childtyping

解决方案


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

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

如需进一步解释,请查看此答案


推荐阅读