我有一個叫做testlib.py
的python文件,它的意圖是定義了其他模塊使用的一些工具類和全局函數。 uselib.py
被設計爲使用testlib.py
中的類/全局函數的客戶端。模塊交叉參考設計問題
因爲某些設計問題的費用,testlib.py
需要參考uselib.py
中定義的某些類Goo
。如果我只是直接導入,會有錯誤信息(在下面發佈)。
只是想知道如何處理這種情況的交叉引用優雅的Python 2.7
uselib.py,
import testlib
class Goo:
def __init__(self):
pass
def checkValue(self):
return "check value in Goo"
print testlib.globalFoo()
f = testlib.Foo()
print f.getValue()
testlib.py,
import uselib
class Foo:
def __init__(self):
pass
def getValue(self):
g = uselib.Goo()
g.checkValue()
return 'get value in class Foo'
def globalFoo():
return 'in global foo'
錯誤消息,
Traceback (most recent call last):
File "/Users/foo/personal/uselib.py", line 1, in <module>
import testlib
File "/Users/foo/personal/testlib.py", line 1, in <module>
import uselib
File "/Users/foo/personal/uselib.py", line 9, in <module>
print testlib.globalFoo()
AttributeError: 'module' object has no attribute 'globalFoo'
你有一個循環導入。 'goo'不需要包含在'uselib'中,我可以告訴 –
@ cricket_007,謝謝,你是什麼意思不需要?它已在uselib.py中定義,我無法更改或移動。 –
循環進口,更一般地說,任何類型的循環依賴,往往是一個強有力的指標,需要重新設計... – twalberg