Python中Module(模块)和Package(包)

Module模块:

在Python中,一个.py文件就称之为一个模块。

比如一个module1.py文件(代码如下),就是一个名字叫module1的模块。

def test():
    print "test case"

模块的导入以及使用:

  1. 直接导入模块
    import module1
    module1.test()
  2. 导入模块并重命名为m1

    import module1 as m
    m.test()
    
  3. 导入模块的部分内容

    from module1 import test
    test()
  4. 导入一个模块并重命名为m2
    from module1 import test as m2
    m2()

Package包:

Package就是模块的集合,每一个Package的根目录下都会有一个__init__.py文件,可以为空或者不为空,主要是为了区分模块名重复,

包的使用以及使用,创建了一个test_package的包:

扫描二维码关注公众号,回复: 5754617 查看本文章

init为空时:

  1. 直接导入包和模块:
    import test_package.module2
    test_package.module2.test()
  2. 导入包和模块并重命名为m2:

    import test_package.module2 as m2
    m2.test()
  3. 导入模块的部分内容:

    from test_package.module2 import test
    test()
  4. 导入模块的部分内容并重命名为m2:

    from test_package.module2 import test as m2
    m2()

init不为空,把类的方法放在init中:

__init__.py:

from module2 import test

然后在其他模块中就可以直接引用这个方法:

from test_package import test
test()

猜你喜欢

转载自blog.csdn.net/weixin_41407477/article/details/84940454