资源描述
单击此处编辑母版标题样式,编辑母版文本样式,第二级,第三级,第四级,第五级,2018/7/27,#,第十七章,模块与包,模块,减少代码重复,模块化,方便管理大型项目,方便定位调试和定位问题,可以动态加载卸载,模块的导入,import,import,模块名,from,模块名,import xxx,from,模块名,import*,搜索顺序,当前文件所在目录,环境变量,PYTHONPATH,目录,Python,默认路径,可以在脚本中动态修改,模块的编写与使用,#hello.py,print(hello.py end),def print_hello():,print(hello world),print(hello.py end),print(_name_),if _name_=_main_:,print(this file is executed directly),跟正常代码编写没有太大区别,import,实际上就是执行一遍模块代码,_name_,可以用来判断是直接执行还是以模块加载,reload,可以重新加载模块,#main.py,import hello,hello.print_hello(),包,#_init_.py,#,在包中,下面两种绝对导入写法效果相同,都是导入,module1,#import pack1.module1,#from pack1 import module1,#,这是相对导入,from.import module1,进一步封装,提供给外界使用的接口,_init_.py,定义要包含的模块,用,_all_,定义接口,初始化一些必要的变量,#module1.py,print(module 1 enter),def hello_world():,print(hello world),def module1_hello():,print(hello from module 1),print(module 1 exit),#demo.py,import pack1#,导入包,pack1.module1.module1_hello(),小结,模块和包都是对代码的进一步封装,目的在于让代码结构和依赖关系更加清晰,模块和包跟普通代码没有什么区别,导入过程就是执行一遍而已,包相对模块来说是更进一步的封装,提供给外界使用的接口,
展开阅读全文