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 相关文章推荐
Python3中使用PyMongo的方法详解
Jul 28 Python
详细解读tornado协程(coroutine)原理
Jan 15 Python
用python爬取租房网站信息的代码
Dec 14 Python
在PyCharm中批量查找及替换的方法
Jan 20 Python
pandas DataFrame 删除重复的行的实现方法
Jan 29 Python
python使用writerows写csv文件产生多余空行的处理方法
Aug 01 Python
django基于cors解决跨域请求问题详解
Aug 06 Python
TensorFlow:将ckpt文件固化成pb文件教程
Feb 11 Python
Python 定义只读属性的实现方式
Mar 05 Python
python查看矩阵的行列号以及维数方式
May 22 Python
Python Map 函数的使用
Aug 28 Python
Django+Celery实现定时任务的示例
Jun 23 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 文件上传进度条的两种实现方法的代码
2007/11/25 PHP
使用VisualStudio开发php的图文设置方法
2010/08/21 PHP
基于empty函数的输出详解
2013/06/17 PHP
PHP中将ip地址转成十进制数的两种实用方法
2013/08/15 PHP
php查询相似度最高的字符串的方法
2015/03/12 PHP
PHP实现权限管理功能示例
2017/09/22 PHP
php设计模式之中介者模式分析【星际争霸游戏案例】
2020/03/23 PHP
查询绑定数据岛的表格中的文本并修改显示方式的js代码
2009/12/15 Javascript
在jquery中处理带有命名空间的XML数据
2011/06/13 Javascript
javascript实现div的拖动并调整大小类似qq空间个性编辑模块
2012/12/12 Javascript
Ext中下拉列表ComboBox组件store数据格式用法介绍
2013/07/15 Javascript
javascript中的=等号个数问题两个跟三个有什么区别
2013/10/23 Javascript
js模拟C#中List的简单实例
2014/03/06 Javascript
随鼠标移动的时钟非常漂亮遗憾的是只支持IE
2014/08/12 Javascript
javascript与css3动画结合使用小结
2015/03/11 Javascript
jQuery插件Tmpl的简单使用方法
2015/04/27 Javascript
javascript中的previousSibling和nextSibling的正确用法
2015/09/16 Javascript
Js得到radiobuttonlist选中值的两种方法(推荐)
2016/08/25 Javascript
10个最优秀的Node.js MVC框架
2017/08/24 Javascript
微信公众平台 客服接口发消息的实现代码(Java接口开发)
2019/04/17 Javascript
vue-cli配置全局sass、less变量的方法
2019/06/06 Javascript
浅入深出Vue之自动化路由
2019/08/06 Javascript
浅谈Vue.set实际上是什么
2019/10/17 Javascript
jQuery开发仿QQ版音乐播放器
2020/07/10 jQuery
Vue切换Tab动态渲染组件的操作
2020/09/21 Javascript
[01:03]DOTA2新的征程 你的脚印值得踏上
2014/08/13 DOTA
Python构造自定义方法来美化字典结构输出的示例
2016/06/16 Python
python音频处理用到的操作的示例代码
2017/10/27 Python
谈一谈基于python的面向对象编程基础
2019/05/21 Python
用python3 urllib破解有道翻译反爬虫机制详解
2019/08/14 Python
Python列表切片常用操作实例解析
2019/12/16 Python
Python实现剪刀石头布小游戏(与电脑对战)
2019/12/31 Python
澳大利亚网上玩具商店:Mr Toys Toyworld
2018/03/25 全球购物
机关工会开展学习雷锋活动总结
2014/03/01 职场文书
主题党日活动总结
2014/07/08 职场文书
大学生村官工作心得体会
2016/01/23 职场文书