我正在使用type()
动态定义一些类,并将它们放置在列表中。但是,我想从模块中使用这些类。例如,如果我的模块是from factories import PersonFactory
,而我创建的动态类是factories.py
,则可以调用PersonFactory
。
这是factories.py
中代码的一部分:
factories = []
for name, obj in models:
factory_name = name + 'Factory' # e.g. PersonFactory
attrs = assemble_factory_attrs(obj, factory_name)
f = type(factory_name, (object,), attrs)
factories.append(f)
# I wanted to "release" the classes into the module definition through `*factories`
# but I get this syntax error: "SyntaxError: can use starred expression only as assignment target"
*factories
谢谢!
最佳答案
您可以将它们添加到模块globals()
中-它看起来像这样:
factories = []
module = globals()
for name, obj in models:
factory_name = name + 'Factory' # e.g. PersonFactory
attrs = assemble_factory_attrs(obj, factory_name)
f = type(factory_name, (object,), attrs)
module[factory_name] = f
factories.append(f)
现在它们既在模块(全局)范围内,又在列表
factories
中。关于python - 将列表中的类解压缩到模块中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30986470/