问题描述
我正在尝试使用 type(名称、基类、属性)
无需将这些类型显式分配给变量,然后使其可用于从其他类导入.
I am trying to create a series of types using type(name, bases, attributes)
without explicitly assigning those types to variables, and then make them available for import from other classes.
到目前为止我所拥有的是这样的
What I have so far is something like this
src/
__init__.py
a/
__init__.py
a_module.py
b/
__init__.py
b_module.py
在 src/a/__init__.py
我有
import inspect
import sys
for c in inspect.getmembers(sys.modules['src.a.a_module'], inspect.isclass):
type(f'{c.__name__}New, (object,), {})
然后我想导入上面在src/b/b_module.py
中定义的类型
Then I would like to import the type defined above in src/b/b_module.py
like
from src.a import AClassNew
a = AClassNew()
但这当然会导致 ImportError: cannot import name
AClassNew`.
but this of course gives an ImportError: cannot import name
AClassNew`.
我意识到我可以放
AClassNew = type('AClassNew', (object,), {})
在 src/a/__init__.py
中,一切正常,但我想对 src/a/a_module.py
中定义的任何类执行此操作没有明确定义它们.
in src/a/__init__.py
and everything will work, but I'd like to do this for any classes defined in src/a/a_module.py
without defining them explicitly.
有没有办法让这个(或类似的东西)工作?
Is there a way to get this (or something similar) to work?
推荐答案
我只是通过更新 src/a/__init__.py
中的 globals()
来解决这个问题.
I got this working by just updating globals()
in src/a/__init__.py
.
for c in inspect.getmembers(sys.modules['src.a.a_module'], inspect.isclass):
new_class_name = f'{c.__name__}New'
new_class = type(new_class_name, (object,), {})
globals[new_class_name] = new_class
这会将具有正确名称的类型添加到此模块的类中,并使其可用于从其他模块导入.
This adds the type with the correct name to the classes of this module and makes it available for import from other modules.
这篇关于如何创建一堆类型并使它们可用于从其他模块导入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!