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 相关文章推荐
Django集成百度富文本编辑器uEditor攻略
Jul 04 Python
Python编程入门的一些基本知识
May 13 Python
python实现爬虫统计学校BBS男女比例(一)
Dec 31 Python
asyncio 的 coroutine对象 与 Future对象使用指南
Sep 11 Python
python 获取图片分辨率的方法
Jan 08 Python
简单了解python 邮件模块的使用方法
Jul 24 Python
Python 实用技巧之利用Shell通配符做字符串匹配
Aug 23 Python
Python3 JSON编码解码方法详解
Sep 06 Python
Python一行代码解决矩阵旋转的问题
Nov 30 Python
在win64上使用bypy进行百度网盘文件上传功能
Jan 02 Python
使用pandas实现筛选出指定列值所对应的行
Dec 13 Python
Python从MySQL数据库中面抽取试题,生成试卷
Jan 14 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进行ip地址掩码运算处理的方法
2016/07/11 PHP
thinkphp表单上传文件并将文件路径保存到数据库中
2016/07/28 PHP
php数据序列化测试实例详解
2017/08/12 PHP
php实现登录页面的简单实例
2019/09/29 PHP
bcastr2.0 通用的图片浏览器
2006/11/22 Javascript
比较详细的关于javascript 解析json的代码
2009/12/16 Javascript
firefox下jQuery UI Autocomplete 1.8.*中文输入修正方法
2012/09/19 Javascript
详解JavaScript中的表单验证
2015/06/16 Javascript
Javascript下拉刷新的简单实现
2017/02/14 Javascript
Bootstrap table学习笔记(2) 前后端分页模糊查询
2017/05/18 Javascript
JS基于正则实现数字千分位用逗号分隔的方法
2017/06/16 Javascript
AugularJS从入门到实践(必看篇)
2017/07/10 Javascript
vue短信验证性能优化如何写入localstorage中
2018/04/25 Javascript
微信小程序实现美团菜单
2018/06/06 Javascript
详解webpack引用jquery(第三方模块)的三种办法
2019/08/21 jQuery
从0到1学习JavaScript编写贪吃蛇游戏
2020/07/28 Javascript
javascript开发实现贪吃蛇游戏
2020/07/31 Javascript
小程序实现列表倒计时功能
2021/01/29 Javascript
python检测主机的连通性并记录到文件的实例
2018/06/21 Python
对python3 中方法各种参数和返回值详解
2018/12/15 Python
python实现Excel文件转换为TXT文件
2019/04/28 Python
Python中typing模块与类型注解的使用方法
2019/08/05 Python
Python使用python-docx读写word文档
2019/08/26 Python
python创建ArcGIS shape文件的实现
2019/12/06 Python
CSS3制作炫酷的自定义发光文字
2016/03/28 HTML / CSS
HTML5利用约束验证API来检查表单的输入数据的代码实例
2016/12/20 HTML / CSS
台湾生鲜宅配:大口市集
2017/10/14 全球购物
澳大利亚排名第一的儿童在线玩具商店:Toy Galaxy
2018/10/06 全球购物
Ted Baker美国官网:英国时尚品牌
2018/10/29 全球购物
安全的后院和健身蹦床:JumpSport
2019/07/15 全球购物
初级软件工程师面试题 Junior Software Engineer Interview
2015/02/15 面试题
兼职学生的自我评价
2013/11/24 职场文书
开工仪式主持词
2014/03/20 职场文书
精神文明建设汇报材料
2014/12/24 职场文书
动态规划之使用备忘录来改进Javascript函数
2022/04/07 Javascript
MySQL串行化隔离级别(间隙锁实现)
2022/06/16 MySQL