循環依賴我有三個文件:如何解決進口
testimports模塊:
#import moduleTwo
import moduleOne
hiString = "Hi!"
moduleOne.sayHi()
ModuleOne的:
import moduleTwo
class sayHi():
moduleTwo.printHi()
ModuleTWO中:
import testimports
def printHi():
print(testimports.hiString)
如果我運行testimports
,我得到:
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'
但是,如果我去掉了import moduleTwo
線testimports
,該方案得到了這一點它停止工作之前:
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'
我如何去解決這個圓依賴性問題?
請搜索SO進行循環導入。有幾百個問題就像你的問題。 http://stackoverflow.com/search?q=%5Bpython%5D+circular+import – 2010-09-18 12:58:22
可能重複的[Python:Cyclic imports](http://stackoverflow.com/questions/744373/python-cyclic-imports) – 2010-09-18 12:58:46