2016-08-24 123 views
0

我正在讀取從here加載的模塊。AttributeError:'模塊'對象沒有屬性'x'

我的目錄mod_a.pymod_b.py之一有兩個文件。

mod_a.py包含以下

print 'at top of mod_a' 
import mod_b 
print 'mod_a: defining x' 
x = 5 

mod_b.py包含

print 'at top of mod_b' 
import mod_a 
print 'mod_b: defining y' 
y = mod_a.x 

上執行mod_a.py文件我得到了以下的輸出:

at top of mod_a 
at top of mod_b 
at top of mod_a 
mod_a: defining x 
mod_b: defining y 
mod_a: defining x 

然而,在執行mod_b.py時I g ot下面的輸出:

at top of mod_b 
at top of mod_a 
at top of mod_b 
mod_b: defining y 
Traceback (most recent call last): 
    File "D:\Python\Workspace\Problems-2\mod_b.py", line 2, in <module> 
    import mod_a 
    File "D:\Python\Workspace\Problems-2\mod_a.py", line 2, in <module> 
    import mod_b 
    File "D:\Python\Workspace\Problems-2\mod_b.py", line 4, in <module> 
    y = mod_a.x 
AttributeError: 'module' object has no attribute 'x' 

有人能解釋一下嗎?

+8

你有一個圓形的進口mod_b

print 'at top of mod_b' import mod_a # Importing a... print 'at top of mod_a' import mod_b # Importing b... print 'at top of mod_b' import mod_a # ... will happen, but... print 'mod_b: defining y' y = mod_a.x # error print 'mod_a: defining x' x = 5 print 'mod_b: defining y' y = mod_a.x 

「痕跡」。不要那樣做;這是你做什麼時發生的事情。 – user2357112

+0

@ user2357112,謝謝,我已經嘗試過這種學習和練習。你能解釋一下這裏的循環進口是如何困擾的嗎? –

+1

https://docs.python.org/2/faq/programming.html#how-can-i-have-modules-that-mutually-import-each-other – user2357112

回答

0

的代碼在這一行

import mod_a 

失敗,因爲它會跑不過mod_a.py,其中進口mod_b.py,其中mod_a.x尚未確定。

爲清楚起見,請參閱此相比mod_a

print 'at top of mod_a' 
import mod_b # Importing b... 

    print 'at top of mod_b' 
    import mod_a # Importing a... 

     print 'at top of mod_a' 
     import mod_b # Recurses... 
     print 'mod_a: defining x' 
     x = 5      # definition 

    print 'mod_b: defining y' 
    y = mod_a.x     # it's defined... no error 

print 'mod_a: defining x' 
x = 5 
相關問題