2013-01-24 72 views
0

我有三個Python文件蟒蛇AttributeError的

one.pytwo.pythree.py

one.py

one.py我打電話

import two as two 
    two.three() 

two.py

def two(): 
    "catch the error here then import and call three()" 
    import three as three 
three.py

def three(): 
    print "three called" 

所以很自然我越來越:

AttributeError: 'function' object has no attribute 'three'

我的問題是:

有沒有辦法有two.py捕獲錯誤然後導入three.py和然後致電three()

__ _ __ _ __ _ __ _ __編輯_ __ _ __ _ __ _ __ _ __ _V
我可以這樣調用:

two().three() 

def two(): 
    import three as three 
    return three 

但我想叫它像這樣:

two.three() 

所以基本上它會自動EXEC高清兩():

+3

你能解釋一下你想要什麼來實現(在更廣泛的層面)? –

+0

假設你的意思是說'從兩個進口的兩個'和'從三個進口的三個'來代替我會是正確的嗎? – neirbowj

+0

我正在嘗試創建一個可以調用的全局對象。 所以導入會發生,然後導入後功能將可用。 – Natdrip

回答

1

這是我提出的解決方案。我承認,我受到你的問題的啓發,試圖弄清楚這一點,所以我自己並沒有完全理解它。神奇的事情發生在two.py,其中嘗試訪問然後調用的three方法由method_router類的__getattr__方法處理。它使用__import__按名稱(字符串)導入指示的模塊,然後通過在導入的模塊上再次調用getattr()來模仿from blah import blah

one.py

from two import two 
two.three() 

兩項。PY

class method_router(object): 
    def __getattr__(self, name): 
     mod = __import__(name) 
     return getattr(mod, name) 

two = method_router() 

three.py

def three(): 
    print("three called") 
+0

我想我可以用這個答案。我會告訴你。 Thx – Natdrip

+0

我想這樣做:two.three()但不會工作它會像這樣工作()。三() def two():import three as three return three – Natdrip

0

當你調用模塊時,被調用的模塊無法自行檢查它是否具有函數,並且如果不遵循替代路徑。你可以包裝two.three()來嘗試except子句來捕獲屬性錯誤。

try: 
    two.three() 
except AttributeError: 
    three.three()