Module模块:
在Python中,一个.py文件就称之为一个模块。
比如一个module1.py文件(代码如下),就是一个名字叫module1的模块。
def test():
print "test case"
模块的导入以及使用:
- 直接导入模块
import module1 module1.test()
-
导入模块并重命名为m1
import module1 as m m.test()
-
导入模块的部分内容
from module1 import test test()
- 导入一个模块并重命名为m2
from module1 import test as m2 m2()
Package包:
Package就是模块的集合,每一个Package的根目录下都会有一个__init__.py文件,可以为空或者不为空,主要是为了区分模块名重复,
包的使用以及使用,创建了一个test_package的包:
init为空时:
- 直接导入包和模块:
import test_package.module2 test_package.module2.test()
-
导入包和模块并重命名为m2:
import test_package.module2 as m2 m2.test()
-
导入模块的部分内容:
from test_package.module2 import test test()
-
导入模块的部分内容并重命名为m2:
from test_package.module2 import test as m2 m2()
init不为空,把类的方法放在init中:
__init__.py:
from module2 import test
然后在其他模块中就可以直接引用这个方法:
from test_package import test
test()