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 基础之字符串string详解及实例
Apr 01 Python
使用python读取txt文件的内容,并删除重复的行数方法
Apr 18 Python
python按时间排序目录下的文件实现方法
Oct 17 Python
python 实现返回一个列表中出现次数最多的元素方法
Jun 11 Python
检测python爬虫时是否代理ip伪装成功的方法
Jul 12 Python
Django 用户认证组件使用详解
Jul 23 Python
Flask框架学习笔记之模板操作实例详解
Aug 15 Python
python 有效的括号的实现代码示例
Nov 11 Python
在Django中实现添加user到group并查看
Nov 18 Python
tensorflow 动态获取 BatchSzie 的大小实例
Jun 30 Python
python如何代码集体右移
Jul 20 Python
python_tkinter弹出对话框创建
Mar 20 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/06/06 PHP
Php-Redis安装测试笔记
2015/03/05 PHP
常见的四种POST 提交数据方式(小总结)
2015/10/08 PHP
PHP实现的文件上传类与用法详解
2017/07/05 PHP
PHP使用Redis实现防止大并发下二次写入的方法
2017/10/09 PHP
PHP中OpenSSL加密问题整理
2017/12/14 PHP
PHP htmlspecialchars() 函数实例代码及用法大全
2018/09/18 PHP
Thinkphp5.0 框架视图view的比较标签用法分析
2019/10/12 PHP
腾讯与新浪的通过IP地址获取当前地理位置(省份)的接口
2010/07/26 Javascript
jquery scroll()区分横向纵向滚动条的方法
2014/04/04 Javascript
基于jQuery的判断iPad、iPhone、Android是横屏还是竖屏的代码
2014/05/11 Javascript
jquery实现表单验证并阻止非法提交
2015/07/09 Javascript
微信公众号开发 自定义菜单跳转页面并获取用户信息实例详解
2016/12/08 Javascript
vue2.0 自定义日期时间过滤器
2017/06/07 Javascript
如何理解Vue的render函数的具体用法
2017/08/30 Javascript
详解IWinter 一个路由转控制器的 Nodejs 库
2017/11/15 NodeJs
JS改变页面颜色源码分享
2018/02/24 Javascript
JS实现数组的增删改查操作示例
2018/08/29 Javascript
JS实现移动端点击按钮复制文本内容
2019/07/28 Javascript
JS立即执行的匿名函数用法分析
2019/11/04 Javascript
Python实现二叉堆
2016/02/03 Python
Python 的描述符 descriptor详解
2016/02/27 Python
VTK与Python实现机械臂三维模型可视化详解
2017/12/13 Python
Python使用Scrapy爬虫框架全站爬取图片并保存本地的实现代码
2018/03/04 Python
Python实现的服务器示例小结【单进程、多进程、多线程、非阻塞式】
2019/05/23 Python
Python解析多帧dicom数据详解
2020/01/13 Python
Python 开发工具通过 agent 代理使用的方法
2020/09/27 Python
浅谈基于Canvas的手绘风格图形库Rough.js
2018/03/19 HTML / CSS
canvas实现漂亮的下雨效果的示例
2018/04/18 HTML / CSS
工作自我评价分享
2013/12/01 职场文书
商场总经理岗位职责
2014/02/03 职场文书
便利店促销方案
2014/02/20 职场文书
2015小学教师年度工作总结
2015/05/12 职场文书
少年犯观后感
2015/06/11 职场文书
小学语文教师研修感悟
2015/11/18 职场文书
Spring Boot 整合 Apache Dubbo的示例代码
2021/07/04 Java/Android