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多线程socket编程之多客户端接入
Sep 12 Python
浅谈使用Python变量时要避免的3个错误
Oct 30 Python
利用pandas读取中文数据集的方法
Jul 25 Python
python钉钉机器人运维脚本监控实例
Feb 20 Python
详解Python中的测试工具
Jun 09 Python
python如何以表格形式打印输出的方法示例
Jun 21 Python
python对常见数据类型的遍历解析
Aug 27 Python
python 导入数据及作图的实现
Dec 03 Python
python基于TCP实现的文件下载器功能案例
Dec 10 Python
使用python matplotlib 画图导入到word中如何保证分辨率
Apr 16 Python
python如何发送带有附件、正文为HTML的邮件
Feb 27 Python
python 判断文件或文件夹是否存在
Mar 18 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 读取大文件的X行到Y行内容的实现代码
2013/06/24 PHP
计算php页面运行时间的函数介绍
2013/07/01 PHP
php array_values 返回数组的所有值详解及实例
2016/11/12 PHP
PHP实现负载均衡下的session共用功能
2018/04/17 PHP
PHP快速排序算法实现的原理及代码详解
2019/04/03 PHP
js 判断 enter 事件
2009/02/12 Javascript
Jquery替换已存在于element上的event的方法
2010/03/09 Javascript
JavaScript下利用fso判断文件是否存在的代码
2010/12/11 Javascript
js控制淡入淡出示例代码
2013/11/12 Javascript
JS简单实现登陆验证附效果图
2013/11/19 Javascript
javascript生成随机大小写字母的方法
2014/02/20 Javascript
jQuery中index()方法用法实例
2014/12/27 Javascript
Bootstrap中定制LESS-颜色及导航条(推荐)
2016/11/21 Javascript
js中Number数字数值运算后值不对的解决方法
2017/02/28 Javascript
js使用xml数据载体实现城市省份二级联动效果
2017/11/08 Javascript
vue购物车插件编写代码
2017/11/27 Javascript
在NPM发布自己造的轮子的方法步骤
2019/03/09 Javascript
JavaScript交换两个变量方法实例
2019/11/25 Javascript
[02:24]DOTA2痛苦女王 英雄基础教程
2013/11/26 DOTA
[02:18]DOTA2英雄基础教程 育母蜘蛛
2014/01/20 DOTA
王纯业的Python学习笔记 下载
2007/02/10 Python
Python利用Beautiful Soup模块创建对象详解
2017/03/27 Python
Django中的Model操作表的实现
2018/07/24 Python
python将list转为matrix的方法
2018/12/12 Python
Django Rest framework认证组件详细用法
2019/07/25 Python
TensorFlow设置日志级别的几种方式小结
2020/02/04 Python
python GUI库图形界面开发之PyQt5输入对话框QInputDialog详细使用方法与实例
2020/02/27 Python
英国建筑用品在线:Building Supplies Online(BSO)
2018/04/30 全球购物
下面这个程序执行后会有什么错误或者效果
2014/11/03 面试题
父亲生日宴会答谢词
2014/01/10 职场文书
先进事迹报告会感言
2014/01/24 职场文书
2014端午节活动策划方案
2014/01/27 职场文书
机电一体化应届生求职信
2014/08/09 职场文书
2014年检验员工作总结
2014/11/19 职场文书
python Polars库的使用简介
2021/04/21 Python
win10键盘驱动怎么修复?Win10键盘驱动修复小技巧
2022/04/06 数码科技