我有两个模块,每个模块都包含一个类。在每个模块中,我想从另一个模块中的类中引用方法。我已经设置了一个小班级来帮助我理解这个概念。我将一个模块导入另一个模块,但仍然出现循环导入错误。据我所知,这是正确的做法,但我仍然遇到错误。这是我的示例类:
a.py 模块:
import b
class A():
def __init__(self):
print("A has run")
def aa():
print("aa has run")
b.B.bb()
b.py 模块:
import a
class B():
def __init__(self):
print("B has run")
def bb():
print("bb has run")
# Run method from class in seperate module
a.A.aa()
这是我的错误: AttributeError: partially initialized module 'b' has no attribute 'B' (most likely due to a circular import)
如果a.py
正在导入b.py
并且b.py
正在导入a.py
,那就是循环导入。通常,您希望重构您的代码,以便您的模块不需要相互导入。如果没有更多地了解您的实际用例,很难给出建议,但可能是这样的:
a.py 模块:
class A():
def __init__(self):
print("A has run")
def aa():
print("aa has run")
b.py 模块:
import a
class B():
def __init__(self):
print("B has run")
def bb():
print("bb has run")
# Run method from class in seperate module
a.A.aa()
c.py 模块
import b
b.B.bb()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句