簡體   English   中英

如何從一個模塊導入類並初始化並在Django中運行

[英]how to import classes from one module and initialise and run it in 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()

首先,請注意, 模塊是指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在我的示例中)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM