如何从一个模块导入类并初始化并在Django中运行

时间:2019-01-09 08:29:16

标签: python django

如何从具有相同结构的模块中的所有.py导入类,并通过对其进行迭代来运行。例如,

module_one:

script_a:
    class A:
        def __init__(self,**kwargs):
            code here
        def run(self,**kwargs):
            code here
        def finish(self,**kwargs):
            code here
script_b:
    class B:
        def __init__(self,**kwargs):
            code here
        def run(self,**kwargs):
            code here
        def finish(self,**kwargs):
            code here
and so on ...

module_two:

script:
    class Run:
        def run_all(self,**kwargs):
            for class in classes_from_module_one:
                c = class()
                c.run()
                c.finish()

1 个答案:

答案 0 :(得分:0)

首先,请注意module指的是python文件,而您所说的模块通常称为包。

现在,对于您的问题,您可以使用在pkgutilimportlibinspect和简单的dir()中找到的实用程序的混合体。例如,使用walk_modulesget_members

# pack/mod_a.py
class A:
    def __init__(self):
        pass

    def run(self):
        print("A run!")

    def finish(self):
        print("A finished!")

# pack/mod_b.py
class B:
    def __init__(self):
        pass

    def run(self):
        print("B run!")

    def finish(self):
        print("B finished!")

# all.py
from importlib import import_module
from inspect import getmembers
from pkgutil import iter_modules


class Run:
    def run_all(self, **kwargs):
        modules = iter_modules(["pack"])
        for module in modules:
            members = getmembers(import_module(f"pack.{module[1]}"))
            my_classes = [member for name, member in members if not name.startswith("_")]
            for cls in my_classes:
                c = cls()
                c.run()
                c.finish()


if __name__ == '__main__':
    run = Run()
    run.run_all()

输出为:

A run!
A finished!
B run!
B finished!

不过,对于此解决方案,您必须注意,getmembers将返回模块的所有成员-包括内置组件,以及导入到模块的实体-因此,您必须实现您可以自行检查以正确过滤掉那些不需要的内容(在我的示例中,请参见简单的startswith)。