pythonimport是怎么实现的?
基本概念:
模块(module):其实就是一个py文件,里面定义了各种变量,函数,类。
模块除了内建模块(可以用过dir(__builtins__)查看有哪些内建函数),就是非内建模块,这一部分模块就需要用import导入。非内建模块经常需要按照第三方库,一般第三方模块在"安装路径\Python\Python35\Lib\site-packages"目录下。
包(package):一个有层次结构的文件目录,里面包含了模块和一些子包,要求包中必须带有一个__init__.py文件。
导入方法:
importmodule_name
frommodule_nameimportmodule_element
不难理解,该过程把module_name.py文件的全部内容加载到内存,把变量类型为’module‘赋值给当前模块的同名变量。
在导入模块时。模块所在文件夹将自动生成一个对应的__pycache__\module_name.cpython-36.pyc文件
怎么加载?——加载方式和用法
方式:
1.importpackage
读这个包的__init__.py,也就是说导入包的本质是执行包下面的__init__.py文件,执行结束后会包名的目录下生成一个"__pycache__/__init__.cpython-36.pyc"文件。
2.importmodule
读整个模块的内容
3.importpackage1.package2.package3.module4
package读取__init__.py,module读取整个模块内容,按顺序读
注意:因为package是读取__init__.py,所以调用的时候必须在__init__.py有引用的东西才能调用,否则会报错。
从哪里加载?
对于python来说,所有被加载到内存的模块都是放在sys.modules里面,所以执行import时会首先去该列表中查询是否已添加。如果已经在sys.modules中,那就简单了,只需要将该module的name添加到我们正在调用该module的本地空间中。如果还没有放在sys.modules中,就需要在sys.path所有路径的目录中去按顺序查找该模块的文件,这些文件一般后缀为".py"、".pyo"、".pyc"、".pyd"、".dll",找到这些模块后就可以将这些模块添加到sys.modules中,再将modulename导入到本地。
以上内容为大家介绍了Python培训之import是怎么实现的?,希望对大家有所帮助,如果想要了解更多Python相关知识,请关注IT培训机构:千锋教育。

相关推荐HOT
更多>>
python函数标注是什么
python函数标注是什么在参数的使用方法中,还有一种解包的情况是需要我们掌握的。比如,将列表或者字典的值转换为函数的参数,就需要用到参数解...详情>>
2023-11-14 14:13:35
python正负索引的使用
python正负索引的使用本文教程操作环境:windows7系统、Python3.9.1,DELLG3电脑。1、说明使用正索引(从左至右)、负索引(从右至左)访问元素,时...详情>>
2023-11-14 13:45:04
python垃圾回收的机制过程
python垃圾回收的机制过程本文教程操作环境:windows7系统、Python3.9.1,DELLG3电脑。1、步骤(1)收集所有容器对象(list,dict,tuple,customClas...详情>>
2023-11-14 13:05:15
pythontry语句的执行原理
pythontry语句的执行原理1、原理分析(1)执行try子句(try和except关键字之间的多行语句)。(2)如果没有异常发生,则跳过except子句并完成try语句...详情>>
2023-11-14 09:37:35热门推荐
技术干货






