Python中几种导入模块的方式总结
作者:jingxian 时间:2021-09-20 08:17:14
模块内部封装了很多实用的功能,有时在模块外部调用就需要将其导入。常见的方式有如下几种:
1 . import
>>> import sys
>>> sys.path
['', 'C:\\Python34\\Lib\\idlelib', 'C:\\Windows\\system32\\python34.zip', 'C:\\Python34\\DLLs', 'C:\\Python34\\lib', 'C:\\Python34', 'C:\\Python34\\lib\\site-packages']
最常见的方式,直接将要导入的模块名称写在后面导入。
2 .from .. import ..
与import类似,只是更明确的要导入的方法或变量,比如:
>>> from sys import path
>>> path
['', 'C:\\Python34\\Lib\\idlelib', 'C:\\Windows\\system32\\python34.zip', 'C:\\Python34\\DLLs', 'C:\\Python34\\lib', 'C:\\Python34', 'C:\\Python34\\lib\\site-packages']
但是会造成命名空间的污染,更推荐使用import。
3 . 用名称字符串导入模块
我们可能想这样导入模块:
>>> import "sys"
SyntaxError: invalid syntax
python import接收的是变量而不是字符串,那将”sys”赋值给一个变量呢?
>>> x="sys"
>>> import x
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
import x
ImportError: No module named 'x'
这样也不行,这样做的意思是导入名为x的模块而非x代表的sys模块。
我们需要用到exec函数:
>>> x="sys"
>>> exec("import "+ x)
>>> sys.path
['', 'C:\\Python34\\Lib\\idlelib', 'C:\\Windows\\system32\\python34.zip', 'C:\\Python34\\DLLs', 'C:\\Python34\\lib', 'C:\\Python34', 'C:\\Python34\\lib\\site-packages']
将导入语句构建成字符串并传递给exec函数执行。
exec缺点是每次执行都要编译,运行多次会影响性能。
更好的方式是使用__import__ 函数。
>>> x="sys"
>>> sys = __import__(x)
>>> sys.path
['', 'C:\\Python34\\Lib\\idlelib', 'C:\\Windows\\system32\\python34.zip', 'C:\\Python34\\DLLs', 'C:\\Python34\\lib', 'C:\\Python34', 'C:\\Python34\\lib\\site-packages']
这种方式需要一个变量保存模块对象,以便后续调用。
标签:python,导入模块
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
scrapy-redis分布式爬虫的搭建过程(理论篇)
2022-04-25 20:49:25
![](https://img.aspxhome.com/file/2023/5/76105_0s.jpg)
python基于itchat实现微信群消息同步机器人
2023-08-02 03:23:51
![](https://img.aspxhome.com/file/2023/3/60733_0s.jpg)
django 微信网页授权认证api的步骤详解
2021-09-15 03:58:40
符合w3c标准flash插入代码,常用flash参数设置
2009-01-20 18:47:00
用python编写第一个IDA插件的实例
2022-01-09 13:05:14
图片预载ImageLoader 1.1 Release
2008-11-04 20:04:00
兼容所有浏览器的设为首页与显示小策略
2009-01-12 18:50:00
![](https://img.aspxhome.com/file/UploadPic/20091/12/make-y-home-page-firefox-57s.png)
C#调用python.exe使用arcpy方式
2021-03-30 05:41:13
![](https://img.aspxhome.com/file/2023/8/71078_0s.jpg)
PHP实现的获取文件mimes类型工具类示例
2023-10-07 09:33:33
INSERT INTO SELECT语句与SELECT INTO FROM语句的一些区别
2012-06-06 19:38:28
asp当中判断函数一览
2010-05-27 12:15:00
js实现用div层模拟的小窗口
2007-12-02 15:01:00
![](https://img.aspxhome.com/file/UploadPic/200712/2/2007122151314277s.gif)
Python 中如何写注释
2022-07-10 21:53:11
PHP的Yii框架的常用日志操作总结
2023-10-30 23:17:03
马化腾关于产品设计与用户体验的培训
2009-02-12 11:45:00
python神经网络使用Keras构建RNN训练
2021-07-19 21:12:15
WEB前端开发高性能优化之JavaScript优化细节
2009-06-10 14:38:00
python 实现数据库中数据添加、查询与更新的示例代码
2023-10-08 04:09:51
ie和firefox中css自动换行实现方法
2008-04-08 12:49:00
用javascript实现select的美化
2007-05-11 16:50:00