本文介绍了如何修复导入的循环依赖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三个文件:

testimports模块:

testimports module:

#import moduleTwo
import moduleOne

hiString = "Hi!"

moduleOne.sayHi()

moduleOne:

moduleOne:

import moduleTwo

class sayHi():
    moduleTwo.printHi()

moduleTwo:

moduleTwo:

import testimports

def printHi():
    print(testimports.hiString)

如果我运行 testimports ,我会得到:

If I run testimports, I get:

Traceback (most recent call last):
  File "..file path snipped../testimports/src/testimports.py", line 2, in <module>
    import moduleOne
  File "..file path snipped../testimports/src/moduleOne.py", line 1, in <module>
    import moduleTwo
  File "..file path snipped../testimports/src/moduleTwo.py", line 1, in <module>
    import testimports
  File "..file path snipped../testimports/src/testimports.py", line 6, in <module>
    moduleOne.sayHi()
AttributeError: 'module' object has no attribute 'sayHi'

但是,如果我取消注释 testimports 中的 import moduleTwo 行,则该程序将在此之前它会停止工作:

If, however, I uncomment the import moduleTwo line in testimports, the program gets to this point before it stops working:

Traceback (most recent call last):
  File "..file path snipped../testimports/src/testimports.py", line 1, in <module>
    import moduleTwo
  File "..file path snipped../testimports/src/moduleTwo.py", line 1, in <module>
    import testimports
  File "..file path snipped../testimports/src/testimports.py", line 2, in <module>
    import moduleOne
  File "..file path snipped../testimports/src/moduleOne.py", line 3, in <module>
    class sayHi():
  File "..file path snipped../testimports/src/moduleOne.py", line 4, in sayHi
    moduleTwo.printHi()
AttributeError: 'module' object has no attribute 'printHi'

我将如何解决这种循环依赖性

How would I go about resolving this circular dependency problem?

推荐答案

重写 testimports.py 可能有帮助:

import moduleOne

hiString = "Hi!"

def main ():
    moduleOne.sayHi()

if __name__ == "__main__":
    main ()

这篇关于如何修复导入的循环依赖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-09 11:24