简体   繁体   English

如何使用python动态创建目录中所有类的实例?

[英]How do I dynamically create instances of all classes in a directory with python?

I'm trying to do something like this: 我正在尝试做这样的事情:

from A.AA import Q, W
from A.AB import E
from A.B.ABA import R
from A.B.ABB import T, Y, U

objs = []
objs.append(Q())
objs.append(W())
objs.append(E())
objs.append(R())
objs.append(T())
# and so on...

The above code is very large, and would take up a bunch of unnecessary time to update it every time I add a new class or module. 上面的代码非常大,每次添加新的类或模块时,都会花费大量不必要的时间来更新它。 Instead, I would like a way to dynamically initialize an object from each of the classes within a directory and all nested directories. 相反,我想要一种从目录和所有嵌套目录中的每个类动态初始化对象的方法。 Something that would abstract down to the following. 可以抽象为以下内容的东西。

objs = []
for py_file in directory:
    for class in py_file:
        objs.append(construct_object_of_type(class))

As a side note, all of those classes inherit from a single base class. 附带说明,所有这些类都继承自单个基类。 This code would also be called from a python file in the top level directory. 该代码也将从顶层目录中的python文件中调用。

If you want to instantiate all the imported objects, you can access them through the global name space with global() built-in function. 如果要实例化所有导入的对象,则可以使用内置的global()函数通过全局名称空间访问它们。

from A.AA import Q, W
from A.AB import E
from A.B.ABA import R
from A.B.ABB import T, Y, U

instances = [obj() for name, obj in globals().items() if not name.startswith('__')]

Also note that basically creating all the instances at once is not a good idea, one reason is that you may don't want to use all of them all ways, and another one might be the problem with passing the specific arguments to constructors for each (or some) class, or if you have some imported objects that you don't want to instantiate, then have to take care of them too, and another problems as well. 还要注意,基本上一次创建所有实例不是一个好主意,一个原因是您可能不想全部使用它们,而另一个可能是将特定参数传递给每个实例的构造函数的问题(或某些)类,或者如果您有一些不想实例化的导入对象,那么也必须照顾它们,以及另一个问题。

So I managed to figure out how to do this. 所以我设法弄清楚该怎么做。

Here's the code for it: 这是它的代码:

import os
import imp
import inspect

obj_list = []

dir_path = os.path.dirname(os.path.realpath(__file__))
pattern = "*.py"

for path, subdirs, files in os.walk(dir_path):
    for name in files:
        if fnmatch(name, pattern):
            found_module = imp.find_module(name[:-3], [path])
            module = imp.load_module(name, found_module[0], found_module[1], found_module[2])
            for mem_name, obj in inspect.getmembers(module):
                if inspect.isclass(obj) and inspect.getmodule(obj) is module:
                    obj_list.append(obj())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM