python - 如何避免循环依赖?
问题描述
我有两个文件,它们都定义了一个类。
project/
__init__.py
thing.py
thinglist.py
thing.py
定义了一个类Thing
,可以输出其他Thing
s的列表:
# thing.py
from project.thinglist import ThingList
class Thing:
def make_more_things(self):
return ThingList(Thing(), Thing())
AThingList
是一个Thing
对象列表,它扩展了列表并添加了一些其他函数:
# thinglist.py
from project.thing import Thing
class ThingList(list):
def __init__(self, *args):
list.__init__(self, *args)
assert all([isinstance(t, Thing) for t in self])
def some_other_method: pass
我们立即遇到了一个问题:循环依赖。Thing
需要ThingList
才能构建ThingLists
。ThingList
需要Thing
以验证它是由且仅由Thing
s 制成的。但是 Python 不会让我Thing
导入thinglist.py
.
为了解决这个问题,我可以将两个类放到同一个文件中。但是它们都很长,为了我自己的理智,我真的不想这样做。我也可以省略isinstance
检查,但是我可能会遇到现在可以轻松解决的错误。
如何在不合并两个文件的情况下避免这种循环依赖?
解决方案
如果指定容器数据类型的唯一目的是执行测试,您可以编写一个具有所有逻辑(追加、类型检查)的类模板类 Container,并且Thing
稍后仅将其子类化为容器类型thing.py
。
例如,在thinglist.py
你会有
class Container:
def __init__(self):
if not hasattr(self, 'type_ref'):
raise NotImplementedError("Type should be set in subclass")
self._data = []
def append(self, elt):
if not isinstance(elt, self.type_ref):
raise TypeError(f'Element should be of type {self.type_ref}')
self._data.append(elt)
... # rest of the logic
并且在thing.py
from thinglist import Container
class ThingList(Container):
type_ref = Thing
推荐阅读
- filter - 如何将某些项目值转换为新项目值?
- discord.py - 如何设置欢迎频道 discord.py?
- python - 无法通过 Python 请求获得“第一个”响应
- kql - 我如何评估可能未提供的价值?
- gdb - 我可以强制 gdb 使用硬件断点吗?
- java - 错误:无法初始化主类库原因:java.lang.NoClassDefFoundError: org/openqa/selenium/Capabilities
- javascript - 如何从数组中的儿童中提取值
- python - 为什么我的 Vimspector 调试会话没有初始化?
- python - 我应该在这条线上改变什么?(语法错误)
- r - 使用 actionButton 后在文本框中保留 selectizeInput 选择