当需要动态加载模块时,可以使用__import__()函数。
函数声明:
__import__(name, globals=None, locals=None, fromlist=(), level=0) -> module
__import__()函数参数较多,本文只简单介绍使用name参数,fromlist参数时的函数调用。
1 PIL模块文件组织方式,用于后续说明:
------------------------------------------------------------------------------------------------------
PIL模块文件组织方式如下(只简单列举出与本示例相关部分):
PIL
— Image.py
其中fromarray为Image.py文件中的一个函数:def fromarray(obj, mode=None):…
-----------------------------------------------------------------------------------------------------
2 函数说明
[1]当需要加载的模块为某一模块的子模块,且fromlist参数为空时,例如PIL.Image,__import__()只能导入最外一层的模块,剩余模块可以使用getattr()函数导入,如下所示:
In [1]: module = __import__("PIL.Image")
In [2]: module.__name__
Out[2]: 'PIL'
In [3]: module = getattr(module, "Image")
In [4]: module.__name__
Out[4]: 'PIL.Image'
[2]当需要直接导入某一模块的子模块时,只需将fromlist参数设置为子模块即可,例如PIL.Image
In [1]: module = __import__("PIL.Image", fromlist=("Image"))
In [2]: module.__name__
Out[2]: 'PIL.Image'
[3]当直接导入某一个*.py文件中的类或函数时,使用__import__()函数会报错,因此参数中不能包含某一个*.py文件中的类或者函数
In [1]: module = __import__("PIL.Image.fromarray")
Traceback (most recent call last):
File "<ipython-input-17-5e9be6d5b59a>", line 1, in <module>
module = __import__("PIL.Image.fromarray")
ModuleNotFoundError: No module named 'PIL.Image.fromarray'; 'PIL.Image' is not a package
3 【sample】
使用__import__()函数导入PIL.Image.fromarray
In [1]: module = __import__("PIL")
In [2]: module.__name__
Out[2]: 'PIL'
In [3]: module = getattr(module, "Image")
In [4]: module.__name__
Out[4]: 'PIL.Image'
In [5]: fun = getattr(module, "fromarray")
In [6]: fun.__name__
Out[6]: 'fromaray'
In [7]: fun
Out[8]: <function PIL.Image.fromarray(obj, mode=None)>