在 Python 中避免循环(循环)导入? [英] Avoiding circular (cyclic) imports in Python?
本文介绍了在 Python 中避免循环(循环)导入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
一种方法是使用 import x,而不使用from"关键字.因此,您可以随处引用具有命名空间的事物.
One way is to use import x, without using "from" keyword. So then you refer to things with their namespace everywhere.
还有别的办法吗?喜欢在 C++ 中做类似 ifnotdef __b__ def __b__ 类型的事情吗?
Is there any other way? like doing something like in C++ ifnotdef __b__ def __b__ type of thing?
推荐答案
将任何一对相互依赖的模块合并为一个模块.然后引入额外的模块以恢复旧名称.
Merge any pair of modules that depend on each other into a single module. Then introduce extra modules to get the old names back.
例如,
# a.py
from b import B
class A: whatever
# b.py
from a import A
class B: whatever
变成
# common.py
class A: whatever
class B: whatever
# a.py
from common import A
# b.py
from common import B
这篇关于在 Python 中避免循环(循环)导入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文