我正在编写两个类Parent
和Child
,因此父级包含多个子级,每个子级都包含对父级的引用,以便最终调用其method()
。由于我使用类型提示( PIP 484 ,主要是为了清晰和可读的代码),我想出了错误:
ValueError: Circular reference detected
由于已在example/child.py
中定义Parent
导入example/parent.py
这一事实。 有谁知道如何摆脱这个错误?
我的Parent
(在example/parent.py
中)如下:
from typing import List
from example.child import Child
class Parent(object):
def __init__(self, children: List[Child] = None) -> None:
self._children = \
{child.name: child for child in children} if children else {}
@property
def children(self) -> List[Child]:
return list(self._children.values())
@children.setter
def children(self, value: List[Child] = None) -> None:
self._children = {child.name: child for child in value} if value else {}
def new_child(self, name: str) -> Child:
child = Child(self, name)
self._children[name] = child
return child
def method(self) -> bool:
return len(self._children) % 2 == 0
我的Child
(在example/child.py
中)取而代之的是:
from typing import TYPE_CHECKING, List
if TYPE_CHECKING:
from example.parent import Parent
class Child(object):
def __init__(self, parent: 'Parent', name: str) -> None:
if parent is None:
raise ValueError("'parent' is invalid: <%s>" % parent)
if name is None or not str(name).strip():
raise ValueError("'name' is invalid: <%s>" % name)
self._parent = parent
self._name = str(name).strip()
@property
def parent(self) -> 'Parent':
return self._parent
@property
def name(self) -> str:
return self._name
def method(self) -> None:
print('we are even' if self._parent.method() else 'we are odd')
请注意,我已经介绍了使用TYPE_CHECKING
变量的技巧,但在这种情况下它没有帮助。提前谢谢!