__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(默认值)表示只执行绝对导入。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

Python内置函数——__import__ 的使用方法相关推荐

  1. Python内置函数sorted()和列表方法sort()排序规则不得不说的事

    Python内置函数sorted()和列表方法sort()可以使用key参数指定排序规则,并且都是稳定排序,也就是说,对于指定规则不能涵盖的元素,本来谁在前面,排好以后谁还是在前面. 直接用代码说话: ...

  2. Python内置函数sorted()和列表方法sort()的排序原理

    问题描述:在Python中,可以使用内置函数sorted()和列表方法sort()对数据进行排序,但要求所有数据支持关系运算符,也就是这些数据本身是可以比较大小的才能进行排序,除非使用key参数明确指 ...

  3. python内置函数__import__

    我们知道import语句是用来导入外部模块的,当然还有from...import...也可以,但是其实import实际上是使用builtin函数__import__来工作的.      在一些程序中, ...

  4. python内置函数format的使用方法 python format函数怎么用

    1.基本语法 format 函数可以接受不限个参数,位置可以不按顺序. 如:"{1} {0} {1}".format("hello", "world& ...

  5. Python内置函数max()高级用法

    不管是排序还是选取最大值或者最小值,都应该有个规则或者顺序,而平时我们所说的最大值或最小值实际上也是在某种排序规则或顺序下的最大值和最小值.Python内置函数max().min()和sorted() ...

  6. Python内置函数—vars的具体使用方法

    本文文章主要介绍了Python内置函数-vars的具体使用方法,分享给大家,具体如下: 英文文档: vars([object]) Return the dict attribute for a mod ...

  7. 列举5个python内置函数和使用方法_python内置函数是什么

    python内置函数如下表 用法及说明 1.abs(),返回数字的绝对值. 2.all(),如果集合中所有元素是true或集合为空集合,返回True. 3.any(),如果集合中有一项元素是true, ...

  8. python内置函数表_python学习系列--python内置函数(一)

    先列出所有的python内置函数,可以看到还是挺多的. abs()        求给定数的绝对值. all()          传入一个列表,只有当列表中所有元素都是真时,该函数返回真. any( ...

  9. 匿名函数python_基于python内置函数与匿名函数详解

    内置函数 Built-in Functions abs() dict() help() min() setattr() all() dir() hex() next() slice() any() d ...

最新文章

  1. python一些常用方法_python 的一些常用方法
  2. Element Swapping
  3. 1028 人口普查 (20 分)(c语言)
  4. jvm系列(一):java类的加载机制
  5. 在python中用import或者from_[转]python基础之---import与from...import....
  6. 利用VC++实现局域网实时传输
  7. docker 容器之间通信_四、Docker 网络原理、分类及容器互联配置
  8. 韩山师范计算机应用技术,二、计算机应用与技术系学生在韩山师范学院“挑战杯”的-….pdf...
  9. (转)金融信息服务业的国际国内竞争格局及新动向
  10. stm32学习------stm32控制L298N电动机
  11. input输入框提示语
  12. mac如何看html5视频播放器,适用于Mac的HTML5视频播放器
  13. PyTorch搭建LSTM实现多变量输入多变量输出时间序列预测(多任务学习)
  14. 在传统软件公司十年深恶痛绝的感受(转)
  15. html分页自动加载数据,硕正控件默认会自动加载数据
  16. 李白 宣州谢朓楼饯别校书叔云
  17. python中print是什么意思中文-python中使用print输出中文的方法
  18. Win11家庭版无法远程连接的解决办法
  19. STM32按键设计一之扫描
  20. 子类内部调用父类成员函数,及子类对象在外部调用父类成员函数问题(C++)

热门文章

  1. Nicetools:定一个小目标,先做它个1000个工具
  2. python做炫酷的界面_用python打造可视化爬虫监控系统,酷炫的图形化界面
  3. python利用faker,输出企业名称、用户名称、手机号、地址信息等测试数据实例
  4. mysql query false_mysql_query() 实施结果一直为false
  5. python线程安全的计数器_+ =运算符在Python中是线程安全的吗?
  6. ubuntu anaconda配置环境变量_Anaconda从下载到环境变量配置(windows)
  7. 二叉树层次遍历python_根据二叉树层序遍历顺序(数组),将其转换为二叉树(Python)...
  8. 短信验证码倒计时代码
  9. 计算机办公软件的使用技巧,实用的Word小技巧集锦(1)办公软件知识 -电脑资料
  10. c语言time_t转oletime,DateTimeFormatter可以格式化日期,但不能读取它自己的格式