[英]how to import classes from one module and initialise and run it in django
How to import classes from all .py in a module with same structure and run by iterating over it. 如何从具有相同结构的模块中的所有.py导入类并通过对其进行迭代来运行。 For Example, 例如,
module_one: 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: module_two:
script:
class Run:
def run_all(self,**kwargs):
for class in classes_from_module_one:
c = class()
c.run()
c.finish()
First of all, please note that module refers to python file, while to what you refer as module is usually called a package. 首先,请注意, 模块是指python文件,而您所称的模块通常称为包。
Now, for your problem, you could use some mixture of utilities found in pkgutil , importlib , and inspect or simple dir()
. 现在,对于您的问题,您可以使用在pkgutil , importlib和inspect或简单的dir()
发现的一些实用程序混合。 For example, using walk_modules
and get_members
: 例如,使用walk_modules
和get_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()
The output is: 输出为:
A run!
A finished!
B run!
B finished!
However for this solution you have to note, that getmembers
will return all members of module - including built-ins, and imported entities to the modules - so you will have to implement your own check to properly filter-out those unwanted (see simple startswith
in my example). 但是,对于此解决方案,您必须注意, getmembers
将返回模块的所有成员-包括内置组件和导入到模块的实体 -因此,您将必须实施自己的检查以正确过滤掉那些不需要的组件(请参阅简单的startswith
在我的示例中)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.