Python内置函数——__import__ 的使用方法


Posted in Python onNovember 24, 2017

__import__() 函数用于动态加载类和函数 。

如果一个模块经常变化就可以使用 __import__() 来动态载入。

语法

__import__ 语法:

__import__(name[, globals[, locals[, fromlist[, level]]]])

参数说明:

name -- 模块名

英文文档:

__import__(name, globals=None, locals=None, fromlist=(), level=0)

This function is invoked by the import statement. It can be replaced (by importing the builtins module and assigning to builtins.__import__) in order to change semantics of the import statement, but doing so is strongly discouraged as it is usually simpler to use import hooks (see PEP 302) to attain the same goals and does not cause issues with code which assumes the default import implementation is in use. Direct use of __import__() is also discouraged in favor of importlib.import_module().

The function imports the module name, potentially using the given globals and locals to determine how to interpret the name in a package context. The fromlist gives the names of objects or submodules that should be imported from the module given by name. The standard implementation does not use its locals argument at all, and uses its globals only to determine the package context of the import statement.

level specifies whether to use absolute or relative imports. 0 (the default) means only perform absolute imports. Positive values for level indicate the number of parent directories to search relative to the directory of the module calling __import__() (see PEP 328 for the details).

When the name variable is of the form package.module, normally, the top-level package (the name up till the first dot) is returned, not the module named by name. However, when a non-empty fromlist argument is given, the module named by name is returned.

说明:

1. 函数功能用于动态的导入模块,主要用于反射或者延迟加载模块。

2. __import__(module)相当于import module

先定义两个模块mian.py和index.py,两个文件在同一目录下:

#index.py
print ('index')

def sayHello():
  print('hello index')

def sayHelloZhCn():
  print('你好 index')
#mian.py
print ('main')

index = __import__('index')
dir(index)
index.sayHello()
index.sayHelloZhCn()

执行main.py,可以证实动态加载了index.py,__import__返回的模块也是index模块

C:\Users\Admin\Documents\Python3\importtest>python main.py
main
index
hello index
你好 index

3. __import__(package.module)相当于from package import name,如果fromlist不传入值,则返回package对应的模块,如果fromlist传入值,则返回package.module对应的模块。

先定义archives包,其中包含user和role两个模块:

#__index__.py
print ('archives.__index__')

def sayHello():
  print('hello archives')
#user.py
print ('user')

def sayHello():
  print('hello user')
#role.py
print ('role')

def sayHello():
  print('hello role')

结构如下:

Python内置函数——__import__ 的使用方法

修改mian.py:

#main.py
print ('main')

archives = __import__('archives')
archives.sayHello()
archives.user

执行main.py,可以证实动态加载了archives包,__import__返回的模块也是archives模块

C:\Users\Admin\Documents\Python3\importtest>python main.py
main
archives.__index__
hello archives
Traceback (most recent call last):
  File "main.py", line 5, in <module>
    archives.user
AttributeError: module 'archives' has no attribute 'user'

修改mian.py:

#main.py
print ('main')

archives = __import__('archives.user')
archives.sayHello()
print(archives.user)

执行main.py,可以证实动态加载了archives包的user模块,__import__返回的模块也是archives模块

C:\Users\Admin\Documents\Python3\importtest>python main.py
main
archives.__index__
user
hello archives
<module 'archives.user' from 'C:\\Users\\Admin\\Documents\\Python3\\import
test\\archives\\user.py'>

修改mian.py:

#main.py
print ('main')

archives = __import__('archives.user',fromlist = ('user',))
archives.sayHello()
print(archives)

执行main.py,可以证实动态加载了archives包的user模块,__import__返回的模块是user模块

C:\Users\Admin\Documents\Python3\importtest>python main.py
main
archives.__index__
user
hello user
<module 'archives.user' from 'C:\\Users\\Admin\\Documents\\Python3\\import
test\\archives\\user.py'>

4. level参数,指定是使用绝对导入还是相对导入。 0(默认值)表示只执行绝对导入。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python基于BeautifulSoup实现抓取网页指定内容的方法
Jul 09 Python
Python实现二叉堆
Feb 03 Python
在Python中执行系统命令的方法示例详解
Sep 14 Python
Python定时发送消息的脚本:每天跟你女朋友说晚安
Oct 21 Python
解决python Markdown模块乱码的问题
Feb 14 Python
8种用Python实现线性回归的方法对比详解
Jul 10 Python
Django 缓存配置Redis使用详解
Jul 23 Python
Python使用Opencv实现图像特征检测与匹配的方法
Oct 30 Python
解决python gdal投影坐标系转换的问题
Jan 17 Python
对python中return与yield的区别详解
Mar 12 Python
Python 爬虫性能相关总结
Aug 03 Python
Python万能模板案例之matplotlib绘制直方图的基本配置
Apr 13 Python
Django中login_required装饰器的深入介绍
Nov 24 #Python
Python多进程库multiprocessing中进程池Pool类的使用详解
Nov 24 #Python
pip安装Python库时遇到的问题及解决方法
Nov 23 #Python
python清理子进程机制剖析
Nov 23 #Python
Python3 加密(hashlib和hmac)模块的实现
Nov 23 #Python
Python2.7基于笛卡尔积算法实现N个数组的排列组合运算示例
Nov 23 #Python
深入理解Python3 内置函数大全
Nov 23 #Python
You might like
php中长文章分页显示实现代码
2012/09/29 PHP
thinkphp特殊标签用法概述
2014/11/24 PHP
PHP实现的简单缓存类
2015/07/29 PHP
iis 7下安装laravel 5.4环境的方法教程
2017/06/14 PHP
文本框水印提示效果的简单实现代码
2014/02/22 Javascript
js实现带关闭按钮始终显示在网页最底部工具条的方法
2015/03/02 Javascript
javascript实现数字倒计时特效
2016/03/30 Javascript
jQuery javascript获得网页的高度与宽度的实现代码
2016/04/26 Javascript
JavaScript中 this 指向问题深度解析
2017/02/21 Javascript
bootstrap基本配置_动力节点Java学院整理
2017/07/14 Javascript
js 开发之autocomplete=&quot;off&quot;在chrom中失效的解决办法
2017/09/28 Javascript
微信小程序使用swiper组件实现类3D轮播图
2018/08/29 Javascript
Vue实现一个图片懒加载插件
2019/03/11 Javascript
判断文字超过2行添加展开按钮,未超过则不显示,溢出部分显示省略号
2019/04/28 Javascript
javascript实现的字符串转换成数组操作示例
2019/06/13 Javascript
Vue监听页面刷新和关闭功能
2019/06/20 Javascript
Jquery如何使用animation动画效果改变背景色的代码
2020/07/20 jQuery
绘制微信小程序验证码功能的实例代码
2021/01/05 Javascript
[54:30]Liquid vs Newbee 2019国际邀请赛小组赛 BO2 第二场 8.15
2019/08/16 DOTA
[01:03:41]完美世界DOTA2联赛PWL S3 DLG vs Phoenix 第一场 12.17
2020/12/19 DOTA
Python提取特定时间段内数据的方法实例
2019/04/01 Python
Opencv实现抠图背景图替换功能
2019/05/21 Python
Python3 执行系统命令并获取实时回显功能
2019/07/09 Python
selenium+python配置chrome浏览器的选项的实现
2020/03/18 Python
HTML5图片预览实例分享
2014/06/04 HTML / CSS
英国受欢迎的运动鞋和街头服装商店:Footasylum
2018/06/12 全球购物
iKRIX意大利网上商店:男女豪华服装和配件
2019/10/09 全球购物
金融专业推荐信
2013/11/14 职场文书
公司人力资源的自我评价
2014/01/02 职场文书
优秀团支部事迹材料
2014/02/08 职场文书
加强作风建设心得体会
2014/10/22 职场文书
2015教师年度思想工作总结
2015/04/30 职场文书
2015秋季新学期开学寄语
2015/05/28 职场文书
运动会班级口号霸气押韵
2015/12/24 职场文书
Nginx + consul + upsync 完成动态负载均衡的方法详解
2021/03/31 Servers
CentOS安装Nginx并部署vue
2022/04/12 Servers