Python从导入的模块创建动态类并设置多个基

nxagd54h  于 2023-01-14  发布在  Python
关注(0)|答案(2)|浏览(90)

我在这里找到了几个例子,但并不是要找什么,这里将试着解释从这个答案试图达到我的结果但并不是要找什么How can I dynamically create derived classes from a base class

我有一个包含许多类的模块

导入模块

import importlib

# are awalable many classes here
forms = importlib.import_module('my_forms')

现在,基于forms,我需要创建一个新类,并向新类中添加forms中可用的所有类的基类
这是我试过的,但找不到分配基地的方法
进口检验员

def create_DynamicClass():
    class DynamicClass(BaseClass):
        pass

    for form_name, class_name in inspect.getmembers(forms):
        for i in class_name():
            # here the code to added all bases to DynamicClass
            
    return DynamicClass()

my_forms模块外观示例

class MyClass1(BaseClass):
    
    attr1 = 1
    attr2 = 2
    
    @coroutine
    def prepare(self):
        # some code for each class

class MyClass2(BaseClass):
    
    attr3 = 3
    attr4 = 4
    
    @coroutine
    def prepare(self):
        # some code for each class

class MyClass3(BaseClass):
    
    attr5 = 5
    attr6 = 6
    
    @coroutine
    def prepare(self):
        # some code for each class

我想达到的结果是以下,将使一个静态类显示所需的结果,但需要动态
我需要创建动态类,因为my_forms模块中可以有任意数量的类

# inherits all classes from my_forms module
class MyResultClass(MyClass1, MyClass2, MyClass3):

    # here get all available attributes from all classes
    

    @coroutine
    def prepare(self):
        # as well need each prepare function for each class as well
        yield MyClass1().prepare()
        yield MyClass2().prepare()
        yield MyClass3().prepare()
kb5ga3dv

kb5ga3dv1#

只需用所有基类声明动态类,将所有基类放在一个列表中,然后用*操作符在class definition语句中解压缩该列表,如下所示:

def createClass(baseClasess):
    class NewClass(*baseClasses):
       pass
    
    return NewClass

DynamicClass = createClass([class1, class2, ...])
b4wnujal

b4wnujal2#

我已经设法找到了一个解决方案,将张贴在这里,如果有任何建议,使它更好将不胜感激

forms = importlib.import_module('my_forms')

class Form(BaseForm):

    @coroutine
    def prepare(self):
        for form_name, class_name in inspect.getmembers(forms, inspect.isclass):
            try:
                yield class_name().prepare()
            except TypeError:
                continue

def createClass(meta):
    for form_name, class_name in inspect.getmembers(forms, inspect.isclass):
        try:
            Form.__bases__ += (class_name, )
            for field in class_name():
                field_type = fl.SelectField() if hasattr(field, 'choices') else fl.StringField()
                setattr(Form, field.name, field_type)
        except TypeError:
            continue
    return Form(meta=meta)

相关问题