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 json模块使用实例
Apr 11 Python
python中while循环语句用法简单实例
May 07 Python
Python中exit、return、sys.exit()等使用实例和区别
May 28 Python
Python中字典创建、遍历、添加等实用操作技巧合集
Jun 02 Python
pandas DataFrame数据转为list的方法
Apr 11 Python
完美解决Pycharm无法导入包的问题 Unresolved reference
May 18 Python
python selenium 对浏览器标签页进行关闭和切换的方法
May 21 Python
Python爬虫爬取电影票房数据及图表展示操作示例
Mar 27 Python
Python3爬虫关于代理池的维护详解
Jul 30 Python
anaconda3安装及jupyter环境配置全教程
Aug 24 Python
python os.listdir()乱码解决方案
Jan 31 Python
Python实战实现爬取天气数据并完成可视化分析详解
Jun 16 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 多进程 解决难题
2009/06/22 PHP
关于svn冲突的解决方法
2013/06/21 PHP
codeigniter数据库操作函数汇总
2014/06/12 PHP
smarty内部日期函数html_select_date()用法实例分析
2015/07/08 PHP
PHP简单操作MongoDB的方法(安装及增删改查)
2016/05/26 PHP
PHP集成环境XAMPP的安装与配置
2018/11/13 PHP
js 控制图片大小核心讲解
2013/10/09 Javascript
Javascript Web Slider 焦点图示例源码
2013/10/10 Javascript
jquery bind(click)传参让列表中每行绑定一个事件
2014/08/06 Javascript
jQuery中hasClass()方法用法实例
2015/01/06 Javascript
简单实现JS对dom操作封装
2015/12/02 Javascript
JQuery统计input和textarea文字输入数量(代码分享)
2016/12/29 Javascript
在Vue中使用echarts的实例代码(3种图)
2017/07/10 Javascript
原生JavaScript实现Ajax异步请求
2017/11/19 Javascript
基于node搭建服务器,写接口,调接口,跨域的实例
2018/05/13 Javascript
Django模板继承 extend标签实例代码详解
2019/05/16 Javascript
layui use 定义js外部引用函数的方法
2019/09/26 Javascript
在Vue中使用antv的示例代码
2020/06/29 Javascript
JavaScript 空间坐标的使用
2020/08/19 Javascript
[40:16]TFT vs Mski Supermajor小组赛C组 BO3 第二场 6.3
2018/06/04 DOTA
在Python中使用cookielib和urllib2配合PyQuery抓取网页信息
2015/04/25 Python
python2.7实现复制大量文件及文件夹资料
2019/08/31 Python
详解python中各种文件打开模式
2020/01/19 Python
python中添加模块导入路径的方法
2021/02/03 Python
HTML5几个设计和修改的页面范例分享
2015/09/29 HTML / CSS
Weekendesk意大利:探索多种引人入胜的周末主题
2016/10/14 全球购物
可持续木材、生态和铝制太阳镜:Proof Eyewear
2019/07/24 全球购物
C#可否对内存进行直接的操作
2015/02/26 面试题
有针对性的求职自荐信
2013/11/14 职场文书
保证书格式
2015/01/16 职场文书
瘦西湖导游词
2015/02/03 职场文书
文体活动总结
2015/02/04 职场文书
2016年高校自主招生自荐信范文
2015/03/24 职场文书
上诉答辩状范文
2015/05/22 职场文书
晚会开场白和结束语
2015/05/29 职场文书
基于Android10渲染Surface的创建过程
2022/08/14 Java/Android