【问题标题】:Interdependence of 2 classes with type hint in PythonPython中2个具有类型提示的类的相互依赖关系
【发布时间】:2018-11-17 00:47:32
【问题描述】:

我想在 Python 3.4+ 中定义 2 个类并使用类型提示,但它们之间存在一些依赖关系。

这是我的代码

class Child():
    def __init__(self, name:str, parent:Parent) -> None:
        """Create a child

        Args:
            name (str): Name of the child
            parent (Parent): Parent (object)
        """
        self.name = name
        self.parent = parent
        parent.give_life(self)


class Parent():
    def __init__(self, name:str) -> None:
        self.name = name
        self.Children = []  # type: List[Child]

    def give_life(self, child:Child) -> None:
        self.Children.append(child)

以及pylint返回的错误:

E0601:在赋值前使用变量'Parent'

如何提示Child类的初始化函数parent参数的类型?

谢谢

【问题讨论】:

标签: python-3.x type-hinting


【解决方案1】:

这是一个前向声明的情况。

为了使其工作,您可以使用字符串 'Parent' 而不是类名称 Parent 来表示函数 Child.__init__(还可以选择使用 Parent.give_life 使其对称)。

生成的代码如下:

class Child():
    def __init__(self, name:str, parent:'Parent') -> None:
        """Create a child

        Args:
            name (str): Name of the child
            parent (Parent): Parent (object)
        """
        self.name = name
        self.parent = parent
        parent.give_life(self)


class Parent():
    def __init__(self, name:str) -> None:
        self.name = name
        self.Children = []  # type: List[Child]

    def give_life(self, child:'Child') -> None:
        self.Children.append(child)

【讨论】:

    猜你喜欢
    • 2019-05-24
    • 1970-01-01
    • 1970-01-01
    • 2023-02-10
    • 1970-01-01
    • 2020-06-12
    • 2011-09-18
    • 2017-05-09
    • 1970-01-01
    相关资源
    最近更新 更多