python import 路徑問題


轉自:https://zhidao.baidu.com/question/1430311163887298579.html

說明:

modules所在的目錄在python里叫package, 下面是一個名為 IsDir的package(實際上就是一個目錄), package下面有4個modules(A, B, C, D)和一個__init__.py文件,目錄結構如下:

1
2
IsDir/
A.py  B.py  C.py  D.py __init__.py

大體來講,有兩種方法可以調用某目錄下(包括遞歸目錄)的modules.

 

一.  __init__.py為空時

 

1.1 以下為調用moduleA的代碼:

1
2
3
#!/usr/bin/env python
from  IsDir  import  A
A.say()

輸出:

1
This is module A!

1.2 如果想調用moduleA,B,C,D呢?

方法1.

1
2
3
4
5
6
7
8
9
#!/usr/bin/env python
from  IsDir  import  A
from  IsDir  import  B
from  IsDir  import  C
from  IsDir  import  D
A.say()
B.say()
C.say()
D.say()

方法2.

1
2
3
4
5
6
7
8
9
10
#!/usr/bin/env python
import  IsDir.A
import  IsDir.B
import  IsDir.C
import  IsDir.D
from  IsDir  import  *
A.say()
B.say()
C.say()
D.say()

錯誤示例1:

1
2
3
#!/usr/bin/env python
import  IsDir.A
A.say()

錯誤示例2:

1
2
3
#!/usr/bin/env python
from  IsDir  import  *
A.say()

錯誤的原因:

          IsDir/目錄下__init__.py 為空時,直接import IsDir.A 或者from IsDir import *是無效的.

從官方文檔里可以看到,__init__.py 里沒有__all__ = [module1,module2,...]時,

from IsDir import * 只能保證IsDir被imported,  所以此時IsDir里的modules是無法被imported,
此時只有如我上面所寫的代碼所示才能正確執行,否則是錯誤的。官方解釋為:import IsDir.A並無任何意義,只有接着執行from IsDir import *后,import IsDir.A語句里的module A才會被定義,所以完整的調用因改為: 1.  import IsDir.A   2. from IsDir import *。

二.   __init__.py用all=[...]指定該package下可以被imported進去的module

 

__init__.py里寫入如下內容:

1
2
cat  IsDir /__init__ .py
__all__ = [ "A" , "B" ]

然后使用之:

1
2
3
4
#!/usr/bin/env python
from  IsDir  import  *
A.say()
B.say()

結果:

1
2
3
% python  test .py 
This is module A!
This is module B!

錯誤實例:

1
2
3
#!/usr/bin/env python
from  IsDir  import  *
C.say()

以上示例之所以錯誤,是因為C並沒有在__all__ = ["A","B"]里制定,由此可見,package IsDir下面的__init__.py里,__all__=[...]具有隔離modules的作用。

 

補充:

module A, B, C,D里我分別只定義了一個method, 例如,以下為module A的code:

1
2
3
cat  IsDir /A .py
def say():
   print  "This is module A!"


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM