详解Python中import机制


Posted in Python onSeptember 11, 2020

Python语言中import的使用很简单,直接使用import module_name语句导入即可。这里我主要写一下"import"的本质。

Python官方定义:

Python code in one module gains access to the code in another module by the process of importing it.

1.定义:

  • 模块(module):用来从逻辑(实现一个功能)上组织Python代码(变量、函数、类),本质就是*.py文件。文件是物理上组织方式"module_name.py",模块是逻辑上组织方式"module_name"。
  • 包(package):定义了一个由模块和子包组成的Python应用程序执行环境,本质就是一个有层次的文件目录结构(必须带有一个__init__.py文件)。

2.导入方法

# 导入一个模块
import model_name
# 导入多个模块
import module_name1,module_name2
# 导入模块中的指定的属性、方法(不加括号)、类
from moudule_name import moudule_element [as new_name]

方法使用别名时,使用"new_name()"调用函数,文件中可以再定义"module_element()"函数。

3.import本质(路径搜索和搜索路径)

  • moudel_name.py
# -*- coding:utf-8 -*-
print("This is module_name.py")

name = 'Hello'

def hello():
 print("Hello")
  • module_test01.py
# -*- coding:utf-8 -*-
import module_name

print("This is module_test01.py")
print(type(module_name))
print(module_name)

运行结果:

E:\PythonImport>python module_test01.py
This is module_name.py
This is module_test01.py
<class 'module'>
<module 'module_name' from 'E:\\PythonImport\\module_name.py'>

在导入模块的时候,模块所在文件夹会自动生成一个__pycache__\module_name.cpython-35.pyc文件。

"import module_name" 的本质是将"module_name.py"中的全部代码加载到内存并赋值给与模块同名的变量写在当前文件中,这个变量的类型是'module';<module 'module_name' from 'E:\\PythonImport\\module_name.py'>

  • module_test02.py
# -*- coding:utf-8 -*-
from module_name import name

print(name)

运行结果;

E:\PythonImport>python module_test02.py
This is module_name.py
Hello

"from module_name import name" 的本质是导入指定的变量或方法到当前文件中。

  • package_name / __init__.py
# -*- coding:utf-8 -*-

print("This is package_name.__init__.py")
  • module_test03.py
# -*- coding:utf-8 -*-
import package_name

print("This is module_test03.py")

运行结果:

E:\PythonImport>python module_test03.py
This is package_name.__init__.py
This is module_test03.py

"import package_name"导入包的本质就是执行该包下的__init__.py文件,在执行文件后,会在"package_name"目录下生成一个"__pycache__ / __init__.cpython-35.pyc" 文件。

  • package_name / hello.py
# -*- coding:utf-8 -*-

print("Hello World")
  • package_name / __init__.py
# -*- coding:utf-8 -*-
# __init__.py文件导入"package_name"中的"hello"模块
from . import hello
print("This is package_name.__init__.py")

运行结果:

E:\PythonImport>python module_test03.py
Hello World
This is package_name.__init__.py
This is module_test03.py

在模块导入的时候,默认现在当前目录下查找,然后再在系统中查找。系统查找的范围是:sys.path下的所有路径,按顺序查找。

4.导入优化

  • module_test04.py
# -*- coding:utf-8 -*-
import module_name 

def a():
 module_name.hello()
 print("fun a")

def b():
 module_name.hello()
 print("fun b")

a()
b()

运行结果:

E:\PythonImport>python module_test04.py
This is module_name.py
Hello
fun a
Hello
fun b

多个函数需要重复调用同一个模块的同一个方法,每次调用需要重复查找模块。所以可以做以下优化:

  • module_test05.py
# -*- coding:utf-8 -*-
from module_name import hello 

def a():
 hello()
 print("fun a")

def b():
 hello()
 print("fun b")

a()
b()

运行结果:

E:\PythonImport>python module_test04.py
This is module_name.py
Hello
fun a
Hello
fun b

可以使用"from module_name import hello"进行优化,减少了查找的过程。

5.模块的分类

内建模块

可以通过 "dir(__builtins__)" 查看Python中的内建函数

>>> dir(__builtins__)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '_', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__','__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round','set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']

非内建函数需要使用"import"导入。Python中的模块文件在"安装路径\Python\Python35\Lib"目录下。

第三方模块

通过"pip install "命令安装的模块,以及自己在网站上下载的模块。一般第三方模块在"安装路径\Python\Python35\Lib\site-packages"目录下。

以上就是详解Python中import机制的详细内容,更多关于Python import机制的资料请关注三水点靠木其它相关文章!

Python 相关文章推荐
详解Python实现按任意键继续/退出的功能
Aug 19 Python
python脚本实现数据导出excel格式的简单方法(推荐)
Dec 30 Python
TensorFlow实现MLP多层感知机模型
Mar 09 Python
python 按照固定长度分割字符串的方法小结
Apr 30 Python
pyQt4实现俄罗斯方块游戏
Jun 26 Python
Python:Numpy 求平均向量的实例
Jun 29 Python
Python 离线工作环境搭建的方法步骤
Jul 29 Python
如何实现在jupyter notebook中播放视频(不停地展示图片)
Apr 23 Python
基于matplotlib中ion()和ioff()的使用详解
Jun 16 Python
解决Python 函数声明先后顺序出现的问题
Sep 02 Python
python中xlrd模块的使用详解
Feb 01 Python
5行Python代码实现一键批量扣图
Jun 29 Python
python使用隐式循环快速求和的实现示例
Sep 11 #Python
Python实现加密的RAR文件解压的方法(密码已知)
Sep 11 #Python
降低python版本的操作方法
Sep 11 #Python
Django crontab定时任务模块操作方法解析
Sep 10 #Python
Django日志及中间件模块应用案例
Sep 10 #Python
Django nginx配置实现过程详解
Sep 10 #Python
使用Python操作MySQL的小技巧
Sep 10 #Python
You might like
php接口和抽象类使用示例详解
2014/03/02 PHP
php 无限级分类,超级简单的无限级分类,支持输出树状图
2014/06/29 PHP
php 模拟 asp.net webFrom 按钮提交事件实例
2014/10/13 PHP
PHP实现数组array转换成xml的方法
2016/07/19 PHP
php实现的rc4加密解密类定义与用法示例
2018/08/16 PHP
php解压缩zip和rar压缩包文件的方法
2019/07/10 PHP
让whoops帮我们告别ThinkPHP6的异常页面
2020/03/02 PHP
通过event对象的fromElement属性解决热区设置主实体的一个bug
2008/12/22 Javascript
javascript获取当前日期时间及其它操作函数
2011/01/11 Javascript
提高javascript效率 一次判断,而不要次次判断
2012/03/30 Javascript
javascript基于HTML5 canvas制作画箭头组件
2014/06/25 Javascript
简单实现兼容各大浏览器的js复制内容到剪切板
2015/09/09 Javascript
AngularJS入门教程之迭代器过滤详解
2016/08/18 Javascript
原生JS发送异步数据请求
2017/06/08 Javascript
JQuery 又谈ajax局部刷新
2017/11/27 jQuery
vue.js系列中的vue-fontawesome使用
2018/02/10 Javascript
讲解vue-router之什么是编程式路由
2018/05/28 Javascript
vue移动端轻量级的轮播组件实现代码
2018/07/12 Javascript
js实现页面多个日期时间倒计时效果
2019/06/20 Javascript
详解Vue-cli3.X使用px2rem遇到的问题
2019/08/09 Javascript
javascript设计模式 ? 策略模式原理与用法实例分析
2020/04/21 Javascript
[48:27]EG vs Liquid 2018国际邀请赛淘汰赛BO3 第二场 8.25
2018/08/29 DOTA
Python创建模块及模块导入的方法
2015/05/27 Python
简单学习Python time模块
2016/04/29 Python
Python程序打包工具py2exe和PyInstaller详解
2019/06/28 Python
Django1.11配合uni-app发起微信支付的实现
2019/10/12 Python
Python List列表对象内置方法实例详解
2019/10/22 Python
Python利用Scrapy框架爬取豆瓣电影示例
2020/01/17 Python
Python continue语句实例用法
2020/02/06 Python
深入理解HTML的FormData对象
2016/05/17 HTML / CSS
什么是Web Service?
2012/07/25 面试题
建筑实习自我鉴定
2013/10/18 职场文书
银行见习期自我鉴定
2014/01/29 职场文书
格列夫游记读书笔记
2015/07/01 职场文书
2019财务管理制度最新范本!
2019/07/09 职场文书
微信小程序结合ThinkPHP5授权登陆后获取手机号
2021/11/23 PHP