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网络编程学习笔记(八):XML生成与解析(DOM、ElementTree)
Jun 09 Python
10个易被忽视但应掌握的Python基本用法
Apr 01 Python
python 生成图形验证码的方法示例
Nov 11 Python
Opencv实现抠图背景图替换功能
May 21 Python
python3+PyQt5 使用三种不同的简便项窗口部件显示数据的方法
Jun 17 Python
在Python中append以及extend返回None的例子
Jul 20 Python
python tkinter控件布局项目实例
Nov 04 Python
Python学习之os模块及用法
Jun 03 Python
Python判断远程服务器上Excel文件是否被人打开的方法
Jul 13 Python
matplotlib 多个图像共用一个colorbar的实现示例
Sep 10 Python
Python 数据可视化神器Pyecharts绘制图像练习
Feb 28 Python
python语言中pandas字符串分割str.split()函数
Aug 05 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查询MySQL大量数据的时候内存占用分析
2011/07/22 PHP
php中使用接口实现工厂设计模式的代码
2012/06/17 PHP
php include和require的区别深入解析
2013/06/17 PHP
php上传图片存入数据库示例分享
2014/03/11 PHP
WIFI万能钥匙密码查询接口实例
2015/09/28 PHP
PHP针对字符串开头和结尾的判断方法
2016/07/11 PHP
PHP实现上一篇下一篇的方法实例总结
2016/09/22 PHP
来自chinaz的ajax获取评论代码
2008/05/03 Javascript
JavaScript 空位补零实现代码
2010/02/26 Javascript
锋利的jQuery jQuery中的DOM操作
2010/03/21 Javascript
ExtJS自定义主题(theme)样式详解
2013/11/18 Javascript
js传中文参数controller里获取参数乱码问题解决方法
2014/01/03 Javascript
javascript基于DOM实现省市级联下拉框的方法
2015/05/14 Javascript
详解微信第三方小程序代开发
2017/06/23 Javascript
vue-cli中的babel配置文件.babelrc实例详解
2018/02/22 Javascript
vue axios数据请求及vue中使用axios的方法
2018/09/10 Javascript
通过JS运行机制的角度说说作用域
2019/03/12 Javascript
ES6入门教程之变量的解构赋值详解
2019/04/13 Javascript
30分钟用Node.js构建一个API服务器的步骤详解
2019/05/24 Javascript
深入浅出vue图片路径的实现
2019/09/04 Javascript
JavaScript 替换所有匹配内容及正则替换方法
2020/02/12 Javascript
jquery实现轮播图特效
2020/04/12 jQuery
js里面的变量范围分享
2020/07/18 Javascript
Vue文本模糊匹配功能如何实现
2020/07/30 Javascript
vue 公共列表选择组件,引用Vant-UI的样式方式
2020/11/02 Javascript
python fabric实现远程操作和部署示例
2014/03/25 Python
通过代码实例展示Python中列表生成式的用法
2015/03/31 Python
Python类的动态修改的实例方法
2017/03/24 Python
详解Python 2.6 升级至 Python 2.7 的实践心得
2017/04/27 Python
python-pyinstaller、打包后获取路径的实例
2019/06/10 Python
StubHub意大利:购买和出售全球演唱会和体育赛事门票
2017/11/21 全球购物
String s = new String(“xyz”);创建了几个String Object?
2015/08/05 面试题
人力资源专员岗位职责
2014/01/30 职场文书
大班幼儿评语大全
2014/04/30 职场文书
英语分层教学实施方案
2014/06/15 职场文书
五年级下册复习计划
2015/01/19 职场文书