我想定义 2 个类并在 Python 3.4+ 中使用类型提示,但它们之间存在一些依赖性。
这是我的代码
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:Using variable 'Parent' before assignment
如何提示 Child
类的初始化函数的 parent
参数类型?
谢谢
最佳答案
这是一个前向声明的情况。
要使其正常工作,您可以使用字符串 'Parent'
而不是函数 Child.__init__
的类名 Parent
(也可以选择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)
关于python-3.x - Python 中带有类型提示的 2 个类的相互依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50735538/