介绍importlib
Python将importlib作为标准库提供。它旨在提供Pythonimport语法和(__import__()函数)的实现。另外,importlib提供了开发者可以创建自己的对象(即importer)来处理导入过程。
那么imp呢?还有一个imp模块提供了import语句接口,不过这个模块在Python3.4已经deprecated了。建议使用importlib来处理。
这个模块比较复杂,文中我们主要探讨如下主题:
- 动态导入
- 检查模块是否可以导入
- 从源文件导入
我们先从动态导入开始。
# 运行环境:python3.6
动态导入
importlib模块支持传递字符串来导入模块。我们先来创建一些简单模块一遍演示。我们分别创建了test.py文件和common文件夹下hello.py文件,代码如下:
test.py内容:
import importlib
def dynamic_import(module):
return importlib.import_module(module)
if __name__=="__main__":
#common.hello 文件夹名.文件名
module=dynamic_import('common.hello')
# hellos:类名,'你好':参数
ob=getattr(module,'hellos')('你好')
# helloworld 函数名
re=getattr(ob,'helloworld')()
print(re)
hello.py内容:
class hellos():
def __init__(self,a):
self.a=a
def helloworld(self):
return self.a
运行test.py结果如下图: