python中的import使用方式笔记
今天有空学习了一下python的import、包、模块、__init__.py之间的俩关系,建立了下面的目录结构
Dir1-
|-test1.py
|-Package1-
|-__init__py
|-module1.py
假设modle1.py内容如下:
def func1():
return ‘this is func1′
那么在test1.py中如何调用到func1()呢?测试了四种方式,每种的import和调用都有微小的区别:
1.
#Content of test1.py
import Pacage1.module1
print Package1.module1.func1()
2.
#Content of test1.py
from Package1 import module1
print module1.func1()
3.
#Content of test1.py
from Package1 import *
print module1.func1()
前面两种有没有__init__.py都行,这种必须要
#Content of test1.py
__all__ = ['module1']
4.
#Content of test1.py
import Package1
print Package1.module1.func1()
__init__.py必需
#Content of test1.py
import module1
Recent Comments