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中的字典详细介绍
Sep 18 Python
Python中的闭包总结
Sep 18 Python
在Python中输入一个以空格为间隔的数组方法
Nov 13 Python
scrapy-redis的安装部署步骤讲解
Feb 27 Python
Python识别快递条形码及Tesseract-OCR使用详解
Jul 15 Python
django获取from表单multiple-select的value和id的方法
Jul 19 Python
python函数修饰符@的使用方法解析
Sep 02 Python
python 实现将小图片放到另一个较大的白色或黑色背景图片中
Dec 12 Python
关于Python解包知识点总结
May 05 Python
Idea安装python显示无SDK问题解决方案
Aug 12 Python
代码复现python目标检测yolo3详解预测
May 06 Python
python神经网络Xception模型
May 06 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防止post重复提交数据的简单例子
2014/06/07 PHP
安装PHP扩展时解压官方 tgz 文件后没有configure文件无法进行配置编译的问题
2020/08/26 PHP
js location.replace与location.reload的区别
2010/09/08 Javascript
基于JQuery的一个简单的鼠标跟随提示效果
2010/09/23 Javascript
jQuery1.6 正式版发布并提供下载
2011/05/05 Javascript
JS焦点图切换,上下翻转
2011/05/12 Javascript
jQuery中bind与live的用法及区别小结
2014/01/27 Javascript
详解jquery中$.ajax方法提交表单
2014/11/03 Javascript
jQuery实现当前页面标签高亮显示的方法
2015/03/10 Javascript
jquery移动端TAB触屏切换实现效果
2020/12/22 Javascript
JavaScript Math 对象常用方法总结
2016/04/28 Javascript
利用Vue实现移动端图片轮播组件的方法实例
2017/08/23 Javascript
从组件封装看Vue的作用域插槽的实现
2019/02/12 Javascript
Vue实现浏览器打印功能的代码
2020/04/17 Javascript
JS求解两数之和算法详解
2020/04/28 Javascript
JS sort方法基于数组对象属性值排序
2020/07/10 Javascript
[03:04]DOTA2超级联赛专访ZSMJ “莫名其妙”的逆袭
2013/05/23 DOTA
[01:15:44]首部DOTA2纪录片今日23时全网上映
2014/03/19 DOTA
[04:28]2014DOTA2国际邀请赛 采访小兔子LGD挺进钥匙体育馆
2014/07/14 DOTA
Python3匿名函数用法示例
2018/07/25 Python
PyQt5实现简易电子词典
2019/06/25 Python
基于Django的乐观锁与悲观锁解决订单并发问题详解
2019/07/31 Python
python-opencv获取二值图像轮廓及中心点坐标的代码
2019/08/27 Python
小 200 行 Python 代码制作一个换脸程序
2020/05/12 Python
浅谈django 重载str 方法
2020/05/19 Python
python画图时设置分辨率和画布大小的实现(plt.figure())
2021/01/08 Python
matplotlib交互式数据光标实现(mplcursors)
2021/01/13 Python
如何将整数int转换成字串String
2014/03/21 面试题
超市5.1促销活动
2014/01/15 职场文书
科技节口号
2014/06/19 职场文书
镇政府副镇长群众路线专题民主生活会对照检查材料
2014/09/19 职场文书
2014年后勤工作总结范文
2014/12/16 职场文书
晶体管单管来复再生式收音机
2021/04/22 无线电
Python基础之函数嵌套知识总结
2021/05/23 Python
原生Javascript+HTML5一步步实现拖拽排序
2021/06/12 Javascript
Docker与K8s关系介绍不会Docker也可以使用K8s
2022/06/25 Servers