python动态加载模块

1 该模块没有调用其他模块

如当前目录下有个add.py文件,文件内容如下:

def add(a, b):
    return a + b

在当前测试文件中写如下测试代码:

def test_func():
    module = __import__('add')
    func = getattr(module, "add")
    print(type(func))
    print(func(1, 2))
打印:

<class 'function'>

说明:

可以看出,只需要通过__import__导入模块即可,再通过getattr即可获取模块中的函数或者类,调用即可

2 该模块相对导入了其他模块

如文件operation.py如下:

from .add import add

class Operation(object):
    def __init__(self, a, b):
        self.a = a
        self.b = b
def add(self):
    return add(self.a, self.b)

可以看出,相对导入了add模块,若还是使用之前的方式执行动态加载,会报错。

正确使用方式为,将要导入的模块,和依赖模块放在同一个包中,如:

+ ti

    _ operation.py

    -  add.py

    - __init__.py

- main.py

在main.py中可以这样测试:

def test_module():
    try:
        import os
        import importlib
        module = importlib.import_module('.operation', 'ti')
        operation_class = getattr(module, "Operation")
        print(type(operation_class))
        print(operation_class(1, 2))
        print(operation_class(1, 2).add())
     except (EnvironmentError, SyntaxError) as err:
 
    	print(err)

这里通过importlib.import_module动态导入,分别为模块名和包名,然后找到Operation类

posted @ 2020-07-23 19:58  小子,你摊上事了  阅读(572)  评论(0)    收藏  举报