转自: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!"
|