Python中import机制详解


Posted in Python onNovember 14, 2017

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 相关文章推荐
python uuid模块使用实例
Apr 08 Python
详解python实现线程安全的单例模式
Mar 05 Python
使用NumPy和pandas对CSV文件进行写操作的实例
Jun 14 Python
使用Python 统计高频字数的方法
Jan 31 Python
使用Python Pandas处理亿级数据的方法
Jun 24 Python
Django实现简单网页弹出警告代码
Nov 15 Python
使用 tf.nn.dynamic_rnn 展开时间维度方式
Jan 21 Python
python如何把字符串类型list转换成list
Feb 18 Python
Python callable内置函数原理解析
Mar 05 Python
基于打开pycharm有带图片md文件卡死问题的解决
Apr 24 Python
python如何进行基准测试
Apr 26 Python
Python多个MP4合成视频的实现方法
Jul 16 Python
AI人工智能 Python实现人机对话
Nov 13 #Python
Python编程实现蚁群算法详解
Nov 13 #Python
Python编程实现粒子群算法(PSO)详解
Nov 13 #Python
人工智能最火编程语言 Python大战Java!
Nov 13 #Python
Python随机生成均匀分布在单位圆内的点代码示例
Nov 13 #Python
python、java等哪一门编程语言适合人工智能?
Nov 13 #Python
K-means聚类算法介绍与利用python实现的代码示例
Nov 13 #Python
You might like
9个实用的PHP代码片段分享
2015/01/22 PHP
PHP通过串口实现发送短信
2015/07/08 PHP
php使用lua+redis实现限流,计数器模式,令牌桶模式
2019/04/04 PHP
javascript数组使用调用方法汇总
2007/12/08 Javascript
JavaScript面向对象之体会[总结]
2008/11/13 Javascript
用JavaScript页面不刷新时全选择,全删除(GridView)
2009/04/14 Javascript
P3P Header解决Cookie跨域的问题
2013/03/12 Javascript
jQuery 绑定事件到动态创建的元素上的方法实例
2013/08/18 Javascript
简单的js图片轮换代码(js图片轮播)
2014/05/06 Javascript
json与jsonp知识小结(推荐)
2016/08/16 Javascript
Javascript将字符串日期格式化为yyyy-mm-dd的方法
2016/10/27 Javascript
详解在React.js中使用PureComponent的重要性和使用方式
2018/07/10 Javascript
深入浅析var,let,const的异同点
2018/08/07 Javascript
Vue $mount实战之实现消息弹窗组件
2019/04/22 Javascript
解决layer弹出层自适应页面大小的问题
2019/09/16 Javascript
jQuery 选择方法及$(this)用法实例分析
2020/05/19 jQuery
vue cli3.0打包上线静态资源找不到路径的解决操作
2020/08/03 Javascript
原生JS实现京东查看商品点击放大
2020/12/21 Javascript
[02:36]DOTA2英雄基础教程 一击致命幻影刺客
2013/12/06 DOTA
python解决字典中的值是列表问题的方法
2013/03/04 Python
Python EOL while scanning string literal问题解决方法
2020/09/18 Python
编写Python爬虫抓取豆瓣电影TOP100及用户头像的方法
2016/01/20 Python
使用Selenium破解新浪微博的四宫格验证码
2018/10/19 Python
浅谈python中get pass用法
2019/03/19 Python
NumPy 数组使用大全
2019/04/25 Python
对python中的os.getpid()和os.fork()函数详解
2019/08/08 Python
django drf框架中的user验证以及JWT拓展的介绍
2019/08/12 Python
PYTHON发送邮件YAGMAIL的简单实现解析
2019/10/28 Python
Python猴子补丁Monkey Patch用法实例解析
2020/03/23 Python
Selenium基于PIL实现拼接滚动截图
2020/04/10 Python
澳大利亚电子产品购物网站:Dick Smith
2017/02/02 全球购物
什么是类的返射机制
2016/02/06 面试题
教师节感恩老师演讲稿
2014/08/28 职场文书
2014最新离职证明范本
2014/09/12 职场文书
运动会表扬稿范文
2015/05/05 职场文书
基于Python实现射击小游戏的制作
2022/04/06 Python