详解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选择排序算法的实现代码
Nov 21 Python
python脚本实现统计日志文件中的ip访问次数代码分享
Aug 06 Python
Python读取ini文件、操作mysql、发送邮件实例
Jan 01 Python
Python中几种操作字符串的方法的介绍
Apr 09 Python
Python的Django框架可适配的各种数据库介绍
Jul 15 Python
在python的类中动态添加属性与生成对象
Sep 17 Python
python  文件的基本操作 菜中菜功能的实例代码
Jul 17 Python
Python 装饰器原理、定义与用法详解
Dec 07 Python
Python 3.8 新功能大揭秘【新手必学】
Feb 05 Python
python随机模块random使用方法详解
Feb 14 Python
关于PyCharm安装后修改路径名称使其可重新打开的问题
Oct 20 Python
selenium+python自动化78-autoit参数化与批量上传功能的实现
Mar 04 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网页游戏学习之Xnova(ogame)源码解读(十六)
2014/06/30 PHP
php通过递归方式复制目录和子目录的方法
2015/03/13 PHP
php上传文件并显示上传进度的方法
2015/03/24 PHP
PHP简单判断字符串是否包含另一个字符串的方法
2016/03/25 PHP
php截取视频指定帧为图片
2016/05/16 PHP
Yii2中cookie用法示例分析
2016/07/18 PHP
PHP AjaxForm提交图片上传并显示图片源码
2016/11/29 PHP
layui框架实现文件上传及TP3.2.3(thinkPHP)对上传文件进行后台处理操作示例
2018/05/12 PHP
ExtJS 简介 让你知道extjs是什么
2008/12/29 Javascript
js实现交换运动效果的方法
2015/04/10 Javascript
JavaScript的面向对象编程基础
2015/08/13 Javascript
xtemplate node.js 的使用方法实例解析
2016/08/22 Javascript
JavaScript中Number对象的toFixed() 方法详解
2016/09/02 Javascript
jQuery中 $ 符号的冲突问题及解决方案
2016/11/04 Javascript
解决vue页面刷新或者后退参数丢失的问题
2018/03/13 Javascript
jquery 动态遍历select 赋值的实例
2018/09/12 jQuery
基于VUE的v-charts的曲线显示功能
2019/10/01 Javascript
老生常谈Python基础之字符编码
2017/06/14 Python
numpy中以文本的方式存储以及读取数据方法
2018/06/04 Python
Python实现去除列表中重复元素的方法总结【7种方法】
2019/02/16 Python
Tensorflow中的降维函数tf.reduce_*使用总结
2020/04/20 Python
python程序需要编译吗
2020/06/19 Python
python实现邮件循环自动发件功能
2020/09/11 Python
英国最大的汽车交易网站:Auto Trader UK
2016/09/23 全球购物
Sunglasses Shop荷兰站:英国最大的太阳镜独立在线零售商和供应商
2017/01/08 全球购物
Stella McCartney官网:成衣、包袋、香水、内衣、童装及Adidas系列
2018/12/20 全球购物
文秘自荐信
2013/10/20 职场文书
求职信模版
2013/11/30 职场文书
团工委书记自荐书范文
2013/12/17 职场文书
写好自荐信的几个要点
2013/12/26 职场文书
财务总监管理岗位职责
2014/03/08 职场文书
教师节班会开场白
2015/06/01 职场文书
复兴之路纪录片观后感
2015/06/02 职场文书
2015暑期工社会实践报告
2015/07/13 职场文书
工作总结之小学教师体育工作范文(3篇)
2019/10/07 职场文书
祝福语集锦:给百岁老人祝寿贺词
2019/11/19 职场文书