2016-09-16 59 views
0

我有一個叫做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' 
+1

你有一個循環導入。 'goo'不需要包含在'uselib'中,我可以告訴 –

+0

@ cricket_007,謝謝,你是什麼意思不需要?它已在uselib.py中定義,我無法更改或移動。 –

+2

循環進口,更一般地說,任何類型的循環依賴,往往是一個強有力的指標,需要重新設計... – twalberg

回答

1

我想出了一個鬼鬼祟祟的黑客:只有import testlib當你uselib.py已經調用__main__功能。在這種情況下,使用if __name__ == "__main__"uselib.py中的檢查很重要。這樣,你可以避免循環導入。 testlib.py具有uselib.py中的所有類,但uselib.py只在需要調用它們時加載testlib.py中的所有內容。

代碼uselib.py

#import testlib 

class Goo: 
    def __init__(self): 
     pass 
    def checkValue(self): 
     return "check value in Goo" 

if __name__ == "__main__": 
    import testlib 
    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' 

輸出:

Chip [email protected] 04:00:[email protected] ~: python uselib.py 
in global foo 
get value in class Foo 

需要注意的是:import testlib也可能是在任何一個叫轉換函數uselib.py,它不需要是__main__。例如: -

代碼另一個uselib.py

#import testlib 

class Goo: 
    def __init__(self): 
     pass 
    def checkValue(self): 
     return "check value in Goo" 
def moretest(): 
    import testlib 
    print testlib.globalFoo() 
    f = testlib.Foo() 
    print f.getValue() 

#if __name__ == "__main__": 
    #import testlib 
    #print testlib.globalFoo() 
    #f = testlib.Foo() 
    #print f.getValue() 

代碼stackoverflow.py

import uselib 
uselib.moretest() 

調用stackoverflow.py

Chip [email protected] 04:30:[email protected] ~: python stackoverflow.py 
in global foo 
get value in class Foo 
+0

感謝Tuan333,聰明的想法。如果我需要引用在main之外的testlib中定義的函數和類,有什麼解決方案? –

+1

你可以嘗試在'uselib.py'中的函數'import' *裏面實際需要'testlib.py'的東西。您調用'import testlib'的函數不需要是'__main__' – TuanDT

+1

已編輯的解決方案。 – TuanDT