Python内置函数——__import__ 的使用方法
作者:十月狐狸 发布时间:2022-07-18 21:02:18
__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')
结构如下:
修改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(默认值)表示只执行绝对导入。
来源:http://www.cnblogs.com/sesshoumaru/p/6130171.html


猜你喜欢
- 在项目开发中,经常出现这样的需求。在新增或修改一个主表数据时,对应的从表也要进行同步,此时我们是怎么操作的了?典型的方法就是对于主表的各数据
- 1、泛型是什么Go1.18增加了对泛型的支持,泛型是一种独立于使用的特定类型编写代码的方式。现在可以编写函数和类型适用于一组类型集合的任何一
- 先看一张我绘制的原理图原理图setImmediate 也是宏任务,在 Node 环境下,微任务还有 process.nextTickJS 中
- 在机器学习或者深度学习中,我们常常碰到一个问题是数据集的切分。比如在一个比赛中,举办方给我们的只是一个带标注的训练集和不带标注的测试集。其中
- 本文实例讲述了js控制div弹出层实现方法。分享给大家供大家参考。具体分析如下:这是个功能很好,且容易调用和控制的弹出层。感兴趣的朋友可以调
- 阅读上一篇:W3C优质网页小贴士(一) 使用 alt 属性描述每幅图像alt 属性有什么用?alt 属性可以在一系列标签中使用(如
- 简单邮件传输协议(SMTP)是一种协议,用于处理在电子邮件服务器之间发送电子邮件和路由电子邮件。Python提供了smtplib模块,该模块
- 字典d = {key1 : value1, key2 : value2, key3 : value3 }键必须是唯一的,但值则不必。值可以取
- 刚开始学习Python的类写法的时候觉得很是麻烦,为什么定义时需要而调用时又不需要,为什么不能内部简化从而减少我们敲击键盘的次数?你看完这篇
- JS是一段一段执行的(以<script>标签来分割),执行每一段之前,都有一个“预编译”,预编译干的活是:声明所有var变量(初
- 一、实战场景Flask 框架实现用户的注册,登录和登出。二、主要知识点flask_login 插件使用SQLAlchemy 基础操作用户基础
- 在计算机程序中,算法是灵魂,是程序的精髓所在。程序执行效率的高低直接取决于算法的优劣,所以计算机算法是计算机课程必修课。算法可以快速计算出我
- #!/usr/bin/env python# name IsOpen.pyimport osimport socketdef IsOpen(
- J2ME是利用HttpConnection建立HTTP连接,然后获取数据,ASP也是利用HTTP协议,因而可以利用J2ME与ASP建立连接,
- 前言:为什么要写这篇文章,因为前段时间有一个开源的github中的项目有一个朋友提交了一个pr看了下是帮忙优化了下代码(十分感谢这位网友)。
- 什么是拼音转换在我们学习语言之前,我们一般会学习拼音来认识汉字,并学会如何读汉字。所以,拼音在对于我们语言的重要性不言而喻。而拼音转换指的是
- 装饰器信号与槽所谓装饰器信号与槽,就是通过装饰器的方法来定义信号与槽函数,具体的使用方法如下@PyQt5.QtCore.pyqtSlot(参
- golang扩容规则举个例子来演示下package mainimport ("fmt")func main() {arr
- 上次遇到一个需要打包下载批量图片的问题,找了一下发现这个好方法,记录一下。首先新建一个zipfile打包类:<?phpclass zi
- 1:安装redigogo get github.com/garyburd/redigo/redis2:引用redigoimport ( &n