python中模块的作用(python基础-模块和包)
1.什么是python的包
包就是一个文件夹 ,里面放着一个个py文件或子包;
在包中可以被调用的一个个py文件 ,我们叫做模块;
如上 ,test就是一个包 、two.py就是test下的一个模块 ,child是子包 ,结构和test包一样;
包的身份证
可以看到test下还有一个__init__.py命名的文件 ,是python包中必须存在的文件 ,是和普通文件夹的区分标志 、类似包的身份证;
2.包的导入import
import package
一般用于两种场景 ,拿到某包下__init__.py文件中中的功能或同级模块下的功能;
如上结构 ,在three.py文件中可以通过import导入test/__init__.py中的方法;
# test/__init__.py def test_init_func(): print(test_init_func) # test2/three.py import test test.test_init_func() # test_init_func还可以在three.py中导入同级模块one.py中的功能;
# test2/one.py def test2_one_func(): print(test2_one_func) # test2/three.py import one one.test2_one_func() # test2_one_func3.模块的导入from .. import ..
通过某个包找到对应的模块;from package import module
3.1 导入同级包中的某模块eg:在main.py中导入test/two.py模块
# test/two.py def test_two_fun(): print(test_two_func) # main.py # 方式一 仍然使用import import test.two test.two.test_two_fun() # test_two_func # main.py # 方式二 使用from...import... from test import two two.test_two_fun() # test_two_func # main.py # 也可以直接导入方法 from test.two import test_two_fun test_two_fun() # test_two_func此时要导入模块中的类时 ,与方法的导入类似 ,导入后实例化一下即可;
# test/two.py class Two(object): @staticmethod def test_two_fun(): print(test_two_func) # main.py from test import two t = two.Two() t.test_two_fun() # test_two_func # 也可以直接导入类 from test.two import Two t = Two() t.test_two_fun() # test_two_func # python的模块导入形式比较灵活 ,按需使用即可 3.2 导入同级包中子包某模块eg: 在main.py中导入test/test2/one.py模块中的方法;
# test/test2/one.py def test_test2_one_func(): print(打印test_test2_one_func) # main.py from test.test2 import one one.test_test2_one_func() # 打印test_test2_one_func # main.py # 也可以直接导入函数 from test.test2.one import test_test2_one_func test_test2_one_func() # 打印test_test2_one_func可以优化下上面from test.test2.one import 的写法,在test/__init__.py中提前导入子包;
# test/__init__.py from .test2.one import test_test2_one_func # init文件中导入同级子包中方法 ,需使用 .子包名 的方式 # main.py # 此时可以直接用import方式导入 ,书写上方便的多 import test test.test_test2_one_func() # 打印test_test2_one_func 3.3 导入同级包中不同子包各自模块此时main.py中要同时导入两个one.py模块;
# test/test2/one.py def test_test2_one_func(): print(打印test_test2_one_func) # test/test3/one.py def test_test3_one_func(): print(打印test_test3_one_func) # main.py from test.test2 import one as test2_one from test.test3 import one as test3_one # 有模块名重复时,为了区分 ,可以使用as重命名下 test2_one.test_test2_one_func() test3_one.test_test3_one_func() 打印test_test2_one_func 打印test_test3_one_func同样也可以借助init文件 ,简写调用方式;
# test/__init__.py from .test2.one import test_test2_one_func from .test3.one import test_test3_one_func # main.py from test import test_test2_one_func, test_test3_one_func # 同一模块导入多个方法时 ,可以合并到一行写 test_test2_one_func() test_test3_one_func() 打印test_test2_one_func 打印test_test3_one_func总结
创心域SEO版权声明:以上内容作者已申请原创保护,未经允许不得转载,侵权必究!授权事宜、对本内容有异议或投诉,敬请联系网站管理员,我们将尽快回复您,谢谢合作!