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 06 Python
Python 实现淘宝秒杀的示例代码
Jan 02 Python
python3.6+django2.0开发一套学员管理系统
Mar 03 Python
详谈python在windows中的文件路径问题
Apr 28 Python
Python数据结构之图的应用示例
May 11 Python
python 分离文件名和路径以及分离文件名和后缀的方法
Oct 21 Python
Python解决pip install时出现的Could not fetch URL问题
Aug 01 Python
Python 调用 Outlook 发送邮件过程解析
Aug 08 Python
Django获取该数据的上一条和下一条方法
Aug 12 Python
浅谈Python3多线程之间的执行顺序问题
May 02 Python
Visual Studio Code搭建django项目的方法步骤
Sep 17 Python
python time()的实例用法
Nov 03 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数组循环操作详细介绍 附实例代码
2013/02/03 PHP
PHP冒泡算法详解(递归实现)
2014/11/10 PHP
php json_encode与json_decode详解及实例
2016/12/13 PHP
PHP实现的mongoDB数据库操作类完整实例
2018/04/10 PHP
PHP多进程通信-消息队列使用
2019/03/08 PHP
PHP抽象类与接口的区别详解
2019/03/21 PHP
laravel实现图片上传预览,及编辑时可更换图片,并实时变化的例子
2019/11/14 PHP
PHP利用curl发送HTTP请求的实例代码
2020/07/09 PHP
Extjs TimeField 显示正常时间格式的代码
2011/06/28 Javascript
JQuery学习笔录 简单的JQuery
2012/04/09 Javascript
jquery数组之存放checkbox全选值示例代码
2013/12/20 Javascript
js中split函数的使用方法说明
2013/12/26 Javascript
javascript如何判断输入的url是否正确
2014/04/11 Javascript
基于jquery实现等比缩放图片
2014/12/03 Javascript
JS实现网页右侧带动画效果的伸缩窗口代码
2015/10/29 Javascript
js立即执行函数: (function ( ){})( ) 与 (function ( ){}( )) 有什么区别?
2015/11/18 Javascript
JavaScript中ES6字符串扩展方法
2016/08/26 Javascript
原生js jquery ajax请求以及jsonp的调用方法
2017/08/04 jQuery
Element Table的row-class-name无效与动态高亮显示选中行背景色
2018/11/30 Javascript
vue axios重复点击取消上一次请求封装的方法
2019/06/19 Javascript
使用vue-router切换页面时实现设置过渡动画
2019/10/31 Javascript
javascript实现贪吃蛇小练习
2020/07/05 Javascript
JS实现audio音频剪裁剪切复制播放与上传(步骤详解)
2020/07/28 Javascript
[01:24:16]2018DOTA2亚洲邀请赛 4.6 全明星赛
2018/04/10 DOTA
Python 冒泡,选择,插入排序使用实例
2015/02/05 Python
Python比较2个时间大小的实现方法
2018/04/10 Python
python 使用sys.stdin和fileinput读入标准输入的方法
2018/10/17 Python
Python单元和文档测试实例详解
2019/04/11 Python
Python celery原理及运行流程解析
2020/06/13 Python
django rest framework 自定义返回方式
2020/07/12 Python
Scrapy项目实战之爬取某社区用户详情
2020/09/17 Python
详解css position 5种不同的值的用法
2019/07/30 HTML / CSS
英国最大的户外商店:Go Outdoors
2019/04/17 全球购物
三下乡活动方案
2014/01/31 职场文书
捐助感谢信
2015/01/22 职场文书
环境卫生标语
2015/08/03 职场文书