从列表中创建多个类

时间:2016-04-12 05:05:00

标签: python python-3.x

是否可以从列表中创建多个类,如下所示:

for cn in ['ABC', 'DEF', 'GHI']:
    class {cn.capitalize()?}(Base):
        __mapper_args__ = {
            'polymorphic_identity': cn.lower(),
        }

注意:在我发现的所有类似标题的问题中,提问者实际上想要从单个类中创建多个对象

1 个答案:

答案 0 :(得分:3)

您可以使用type在运行时创建新类:

In [17]: class_names = ['ABC', 'DEF', 'GHI']

In [18]: classes = {name: type(name.capitalize(), (Base,),
                      {'__mapper_args__': {'polymorphic_identity': name.lower()}})
           for name in class_names}

In [19]: classes['DEF']
Out[19]: __main__.Def

In [20]: classes['ABC']().__mapper_args__
Out[20]: {'polymorphic_identity': 'abc'}

In [21]: import inspect

In [22]: inspect.getmro(classes['GHI'])
Out[22]: (__main__.Ghi, __main__.Base, object)