【问题标题】:Python 3 typing annotation and parent-child designPython 3 打字注解和父子设计
【发布时间】:2019-09-23 03:53:57
【问题描述】:

我正在编写一些 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 类没有定义。这是合乎逻辑的,因为它属于Parent 类。

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

【问题讨论】:

标签: python parent-child typing


【解决方案1】:

这是一个循环依赖问题。

当您的代码运行并遇到Parent 类时,它会查找Child 类定义,但它是在之后定义的,因此找不到它并抛出错误!

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

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

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

【讨论】:

    【解决方案2】:

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

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

    更多解释请看this answer

    【讨论】:

      猜你喜欢
      • 2017-06-07
      • 2022-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-07
      • 1970-01-01
      • 2010-09-15
      • 1970-01-01
      相关资源
      最近更新 更多