python内置函数__import__()动态加载模块

当需要动态加载模块时,可以使用__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)> 
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值