Python __import__() 函数
__import__() 是 Python 中用于动态导入模块的内置函数。
__import__() 是 import 语句的底层实现,允许在运行时动态导入模块。它对于插件系统、延迟加载等场景非常有用。
单词释义: __import__ 是 Python 的内置导入函数。
基本语法与参数
语法格式
__import__(name, globals=None, locals=None, fromlist=(), level=0)
参数说明
- 参数 name:
- 类型: 字符串
- 描述: 要导入的模块名。
- 参数 fromlist(可选):
- 类型: 元组
- 描述: 要从模块中导入的子模块或属性列表。
函数说明
- 返回值: 返回导入的模块对象。
实例
示例 1:基础用法
实例
# 动态导入模块
os = __import__('os')
print(os.getcwd()) # 输出: 当前工作目录
# 导入子模块
requests = __import__('collections', fromlist=['Counter'])
print(requests.Counter) # 输出: <class 'collections.Counter'>
os = __import__('os')
print(os.getcwd()) # 输出: 当前工作目录
# 导入子模块
requests = __import__('collections', fromlist=['Counter'])
print(requests.Counter) # 输出: <class 'collections.Counter'>
运行结果:
导入模块的方式。
示例 2:动态导入
实例
# 根据字符串导入模块
module_name = "json"
mod = __import__(module_name)
print(mod.dumps({"key": "value"})) # 输出: {"key": "value"}
# 动态导入多个模块
modules = ['math', 'random', 'datetime']
for name in modules:
mod = __import__(name)
print(f"{name}: {mod.__name__}")
# 延迟导入(按需加载)
def get_module(mod_name):
return __import__(mod_name)
math_mod = get_module('math')
print(math_mod.sqrt(16)) # 输出: 4.0
module_name = "json"
mod = __import__(module_name)
print(mod.dumps({"key": "value"})) # 输出: {"key": "value"}
# 动态导入多个模块
modules = ['math', 'random', 'datetime']
for name in modules:
mod = __import__(name)
print(f"{name}: {mod.__name__}")
# 延迟导入(按需加载)
def get_module(mod_name):
return __import__(mod_name)
math_mod = get_module('math')
print(math_mod.sqrt(16)) # 输出: 4.0
运行结果:
动态导入在实际应用中有多种用途。
__import__() 是 Python 动态导入机制的核心。
Python3 内置函数
点我分享笔记