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实现的tab文件操作类分享
Nov 20 Python
Python编程给numpy矩阵添加一列方法示例
Dec 04 Python
利用python解决mysql视图导入导出依赖的问题
Dec 17 Python
Python实现多属性排序的方法
Dec 05 Python
python 利用pandas将arff文件转csv文件的方法
Feb 12 Python
python-itchat 获取微信群用户信息的实例
Feb 21 Python
python多线程下信号处理程序示例
May 31 Python
python opencv把一张图片嵌入(叠加)到另一张图片上的实现代码
Jun 11 Python
解决TensorFlow程序无限制占用GPU的方法
Jun 30 Python
用pandas划分数据集实现训练集和测试集
Jul 20 Python
详解BeautifulSoup获取特定标签下内容的方法
Dec 07 Python
Django中celery的使用项目实例
Jul 07 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入门小知识
2008/03/24 PHP
Search File Contents PHP 搜索目录文本内容的代码
2010/02/21 PHP
php.ini修改php上传文件大小限制的方法详解
2013/06/17 PHP
PHP 过滤页面中的BOM(实现代码)
2013/06/29 PHP
PHP中使用addslashes函数转义的安全性原理分析
2014/11/03 PHP
laravel 5 实现模板主题功能(续)
2015/03/02 PHP
php生成毫秒时间戳的实例讲解
2017/09/22 PHP
yii框架结合charjs统计上一年与当前年数据的方法示例
2020/04/04 PHP
JS代码优化技巧之通俗版(减少js体积)
2011/12/23 Javascript
Jquery命名冲突解决的五种方案分享
2012/03/16 Javascript
jquery动态增加text元素以及删除文本内容实例代码
2013/07/01 Javascript
JavaScript实现的伸展收缩型菜单代码
2015/10/14 Javascript
javascript函数命名的三种方式及区别介绍
2016/03/22 Javascript
javascript使用btoa和atob来进行Base64转码和解码
2017/03/20 Javascript
Vuex和前端缓存的整合策略详解
2017/05/09 Javascript
使用watch在微信小程序中实现全局状态共享
2019/06/03 Javascript
Vue使用自定义指令实现拖拽行为实例分析
2020/06/06 Javascript
vue实现简单计算商品价格
2020/09/14 Javascript
python删除过期文件的方法
2015/05/29 Python
Python实现进程同步和通信的方法
2018/01/02 Python
APIStar:一个专为Python3设计的API框架
2018/09/26 Python
Python读取分割压缩TXT文本文件实例
2020/02/14 Python
python3将变量写入SQL语句的实现方式
2020/03/02 Python
python 实现aes256加密
2020/11/27 Python
实例讲解CSS3中的box-flex弹性盒属性布局
2016/06/09 HTML / CSS
Html5之webcoekt播放JPEG图片流
2020/09/22 HTML / CSS
Ticketmaster德国票务网站:购买音乐会和体育等门票
2016/11/14 全球购物
后勤副校长自我鉴定
2013/10/13 职场文书
服装设计专业毕业生推荐信
2013/11/09 职场文书
学院书画协会部门职责
2013/11/28 职场文书
茶叶店创业计划书范文
2014/01/19 职场文书
推广普通话演讲稿
2014/05/23 职场文书
政工例会汇报材料
2014/08/26 职场文书
物业前台接待岗位职责
2015/04/03 职场文书
学校艾滋病宣传活动总结
2015/05/09 职场文书
暖春观后感
2015/06/08 职场文书