我正在使用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
谢谢!
答案 0 :(得分:1)
您可以将它们添加到模块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
中。